31. Next Permutation (JAVA)

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);
        }
    }

}

寻找规律:

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

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

猜你喜欢

转载自www.cnblogs.com/qionglouyuyu/p/10797450.html