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


题意:
全排列问题,用过c++STL的next_permutation的都用该知道。
给定一个序列,找到该序列排序的下一个序列,要求不能使用额外的空间。
题目也给例子了比如1,2,3的下一个排列是1,3,2。


思路:
如果是按照题目从小到大顺序,我们应该先从后往前找到满足向另元素顺序为小于顺序的第一对元素a[i] < a[i+1],因为我们所找到的第一个a[i]正是我们下一次全排列的需要交换的元素之一,比如1,4,3,2,a[i]就是1 (有点类似进位的感觉),接着从末尾找到第一个比a[i]大的元素a[j],在1,4,3,2中是2,也就是次小于1的,然后交换a[i]和a[j],此时序列变为2,4,3,1,因为交换完1,2后,此刻为2开头最小的全排列,所以排序2后面的所有数字(从小到大),变为2,1,3,4,还是类似进位的感觉。


代码:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.size() < 2){
            return;
        }
        int i,j;
        //找i
        for(i = nums.size()-2; i >= 0; --i){
            if(nums[i] < nums[i+1]){
                break;
            }
        }
        //找j
        for(j = nums.size()-1; j > i; --j){
            if(nums[i] < nums[j]){
                break;
            }
        }
        int t;
        //交换i,j
        if(i >= 0){
            t = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
        //原本我们因该排序,找j时是nums[i]<nums[j],后面的元素是有序的,只不过是逆序,我们reverse即可。不过sort也AC了
        //sort(nums.begin()+i+1, nums.end());
        reverse(nums.begin()+i+1, nums.end());
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏天的技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值