【LeetCode】31. Next Permutation

来源:互联网 发布:大数据access和mysql 编辑:程序博客网 时间:2024/06/07 04:43

题目描述

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,23,2,11,2,31,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
原创粉丝点击