Leetcode31 Next Permutation

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

Solution

  • 可以举例观察特点。
    • 345
    • 354
    • 435
    • 453
    • 534
    • 543
    • 345
  • 如上所述,实际操作过程可以分为三步:
    • 第一步,从后往前找,找到第一个降序,比如453,45这里是一个降序,降序处的数为4;
    • 第二步,从后往前找找到第一个比4大的那个数,这里是5,交换4和5的位置;
    • 第三步,将原先4位置后面的数进行翻转,比如这里是先得到543,然后再将43翻转得到最终的答案为534。
  • 用代码表示如下:
public class Solution {
    public void nextPermutation(int[] nums) {
        int n = nums.length;
        int i = n-2, j = n-1, temp;
        for(;i>=0;i--) if(nums[i]<nums[i+1]) break;//从后往前找到第一个降序
        if(i>=0){
            temp = nums[i];
            for(;j>=0;j--) if(nums[j]>temp) break;//从后往前找到第一个比降序处的数大的数
            nums[i] = nums[j];//交换这两个数
            nums[j] = temp;
        }
        for(i++,j=n-1;i<j;i++,j--){//翻转后面的所有数
            temp = nums[j];
            nums[j] = nums[i];
            nums[i] = temp;
        }        
    }
}
  • 当然,有些解法里面在第二步的时候用二分法去找比4大的那个数,这样运行速度稍微会好些,但是时间复杂度仍为O( N <script type="math/tex" id="MathJax-Element-9">N</script>),并且代码也要更加复杂一些。感兴趣的可以自己尝试去实现一下。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值