码迷,mamicode.com
首页 > 编程语言 > 详细

31. Next Permutation (JAVA)

时间:2019-04-30 21:48:31      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:solution   blank   algorithm   一个   wiki   ati   cal   规律   targe   

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

 

 

class Solution {
    public void nextPermutation(int[] nums) {
        int tmp;
        int i;
        int j;
        for(i = nums.length-2; i >= 0; i--){
            if(nums[i] < nums[i+1]) break;
        }
        
        if(i >= 0){
            //find the smallest num in the right which is larger than num[i]
            for(j = nums.length-1; j >= i; j--){
                if(nums[j] > nums[i]) break;
            }
            
            //swap these two num
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
            
            //sort
            Arrays.sort(nums, i+1, nums.length);
        }
        else{
            Arrays.sort(nums);
        }
    }

}

 

寻找规律:

- 从右向左扫描,找到小于右侧数字的第一个数字

- 将右侧大于它的最小的那个数放在该位,它和其余右侧的数字从小到大排列放在右侧。

31. Next Permutation (JAVA)

标签:solution   blank   algorithm   一个   wiki   ati   cal   规律   targe   

原文地址:https://www.cnblogs.com/qionglouyuyu/p/10797450.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!