31. 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

题目分析

看如下序列:

3 5 4 2 1

求其下一个排序数的思路:
1. 逆序搜索,找到第一个满足

nums[i1]<nums[i]
的位置,在 i=1 处。并且 i~n-1 序列一定是一个逆序序列
2. 交换 nums[i-1] 和 i>=1子序列的最小值。 最小值为 4;即交换 3 和 4,得到的序列为: 4 5 3 2 1
3. 将i>=1的序列反转,即 4 1 2 3 5

代码

时间复杂度为O(n),空间复杂度为O(1)。

public class Solution {
    public void NextPermutation(int[] nums) {
        if(nums.Length<=1) return;
        int i = findIndex(nums);
        if(i==0)//no existence nums[i-1]<nums[i]
            sortReverseNums(nums,0,nums.Length-1);
        else {
            int swap1 = findSwapIndex(nums,i);
            swap(nums,i-1,swap1);
            sortReverseNums(nums,i,nums.Length-1);
        }
    }

    //find the first nums[i-1]<nums[i] of i
    private int findIndex(int[] nums){
        int n=nums.Length-1;
        while(n>0){
            if(nums[n-1]<nums[n])
                break;
            n--;
        }
        return n;
    }

    //find the swap index
    //assert: i>=1
    private int findSwapIndex(int[] nums, int i){
        int n=nums.Length-1;
        int swap1=nums[i-1];
        int index;
        for(index=n; index>=i;index--){
            if(swap1<nums[index])
                break;
        }
        return index;
    }

    private void swap(int[] nums, int i, int j){
        int tmp=nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }

    private void sortReverseNums(int[] nums, int start, int end){
        for(int i=start; i<=(start+end)/2;i++){
            swap(nums,i,start+end-i);
        }
    }


}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值