31. Next Permutation (JAVA)

Posted qionglouyuyu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
        }
    }

}

 

寻找规律:

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

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

以上是关于31. Next Permutation (JAVA)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode - 31. Next Permutation

Python31. Next Permutation

LeetCode OJ 31. Next Permutation

LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

31. Next Permutation

31. Next Permutation