0031_Next Permutation

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, do not allocate 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

JAVA

方法一

  此题是求在升序的全排列中,输入的数组的下一个排列,当输入的数组是最后一个排列时,返回该全排列的第一个排列。写一些排列,从中寻找规律。
1 2 3 6 8
1 2 3 8 6
1 2 6 3 8
1 2 6 8 3
1 2 8 3 6
1 2 8 6 3
1 3 2 6 8
1 3 2 8 6
  通过观察可以发现,每个排列的下一个排列,都是将已经参与排列的部分中的大于且最接近未排列部分最后一位的数进行交换,然后对已经参与排序的部分进行升序排列,且经过观察,将该部分反转正好可以得到升序。以1 2 8 6 3为例,通过寻找最后一个i使nums[i] < nums[i+1],可以知道nums[i]即为未参与排序部分的最后一个数字,此时i=1,nums[i]=2。然后在已排序部分[i+1, nums.length-1]中寻找大于nums[i]=2且最接近它的数,此时j=4,nums[j]=3。交换nums[i]和nums[j],得到序列1 3 8 6 2,此时对[i+1, nums.length]进行反转即可得到结果。对于1 2 6 3 8等情况同样适用。
  时间效率在50%左右。但是需要注意边界值得判断。

public class Solution {
    public void nextPermutation(int[] nums) {
        int lastLittleIndex = -1;
        int colseLagerIndex = -1;

        for(int i = 0; i < nums.length - 1; ++i){
            if(nums[i] < nums[i+1]){
                lastLittleIndex = i;
            }
        }
        //加入lastLittleIndex >= 0的判断,当输入数组为降序时,lastLittleIndex=-1,访问nums[lastLittleIndex]会越界。如果在此循环体之外再加入if判断的话,会影响程序整体结构,影响最后部分if判断构成的反转操作。
        //i <= nums.length - 1的比较重需要加入等号,这样当输入为升序时,lastLittleIndex+1后与数组长度相同,才能进入循环体内进行判断
        //nums[i] <= nums[colseLagerIndex]的比较重需要加入等号,这样当有重复的字符时,才能将colseLagerIndex定位到最后
        for(int i = lastLittleIndex + 1; lastLittleIndex >= 0 && i <= nums.length - 1; ++i){
            if(i > 0 && nums[i] > nums[lastLittleIndex]){
                if(colseLagerIndex == -1 || nums[i] <= nums[colseLagerIndex]){
                    colseLagerIndex =i;
                }
            }
        }

        if(colseLagerIndex == -1){
            reverse(nums, 0, nums.length-1);
        }else{
            int temp = nums[lastLittleIndex];
            nums[lastLittleIndex] = nums[colseLagerIndex];
            nums[colseLagerIndex] = temp;
            reverse(nums, lastLittleIndex+1, nums.length-1);
        }        
    }

    public void reverse(int[] nums, int start, int end){
        int temp;
        for(int i = start, j = end; i < j; ++i, --j){
            temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值