首页 > 编程语言 > 详细

31. Next Permutation (JAVA)

时间:2019-04-30 20:51:13      阅读:137      评论:0      收藏:0      [点我收藏+]

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)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!