【LeetCode】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,31,3,2
3,2,11,2,3
1,1,51,5,1

解题思路

因为要找的是比当前排列大一点的下一个排列,所以应该通过调整最靠后面的数字的排序来实现。
从后往前找,如果数字一直增大,那是没有办法通过调整后面的排列来得到更大的排列的。
当找到一个数字,它比后一个数字小时,才可以开始实行交换。将那个数字与已经遍历过的部分中恰好比它大一点的值进行交换,然后反转后半部分,即让它由从后往前的递增变为递减。

AC代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if (nums.size() < 2)
            return;

        int startIdx = nums.size() - 2;
        while (startIdx >= 0) {
            if (nums[startIdx] >= nums[startIdx + 1]) {
                startIdx--;
            }
            else {
                //get the upper bound
                int upperIdx = nums.size() - 1;
                for (; upperIdx > startIdx; --upperIdx) {
                    if (nums[upperIdx] > nums[startIdx])
                        break;
                }
                //swap and break
                int temp = nums[startIdx];
                nums[startIdx] = nums[upperIdx];
                nums[upperIdx] = temp;
                break;
            }
        }
        sort(nums.begin() + startIdx + 1, nums.end());
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值