LeetCode 31. Next Permutation

Description: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
2,3,1 → 3,1,2

思路:按照字典从小到大排序,求当前排列的下一个更大(这是重点)的排列,如果已经是最大排列,则下一个排列是最小排列。理解了这2层意思,就很好写了。数组中的数字从左往右级别依此降低,所以遍历从右边开始,共2层遍历,第一层遍历的是要替换的数字numL,第二层遍历numL右边的数字numR,比较numR>numL,true则替换,然后在给numL(替换后是numR)右边的数字排序,确保是下一个更大的排列。

参考代码:

void MySolution::nextPermutation(vector<int>& nums) {
    int len = nums.size();
    for (int i = len-2; i >= 0; i--) {
        for (int j = len-1; j > i; j--) {
            if (nums[j] > nums[i]) {
                int temp = nums[j];
                nums[j] = nums[i];
                nums[i] = temp;
                sort(nums.begin() + i + 1, nums.end());
                return;
            }
        }
    }
    reverse(nums.begin(), nums.end());
}

测试结果:
Runtime: 8 ms, faster than 78.21% of C++ online submissions for Next Permutation.
Memory Usage: 8.6 MB, less than 94.62% of C++ online submissions for Next Permutation.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值