Skip to content

Files

Latest commit

 

History

History
64 lines (49 loc) · 2.04 KB

31-next-permutation.md

File metadata and controls

64 lines (49 loc) · 2.04 KB

31. Next Permutation - 下一个排列

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1


题目标签:Array

题目链接:LeetCode / LeetCode中国

题解

从右往左探测,若是不减序列,就反转序列;否则将出现减少处的值与右侧比它大且最接近的值进行交换,并对右侧进行升序排列。

Language Runtime Memory
cpp 12 ms 1.9 MB
class Solution {
public:
    void printVector(vector<int>& nums) {
        cout << "[ ";
        for (int i : nums) {
            cout << i << " ";
        }
        cout << "]" << endl;
    }

    void nextPermutation(vector<int>& nums) {
        if (nums.size() < 2) { return; }
        int p = nums.size() - 2;
        while (p >= 0 && nums[p] >= nums[p+1]) {
            p--;
        }
        if (p == -1) {
            reverse(nums.begin(), nums.end());
        } else {
            for (int i=nums.size()-1; i>p; --i) {
                if (nums[i] > nums[p]) {
                    nums[p] ^= nums[i];
                    nums[i] ^= nums[p];
                    nums[p] ^= nums[i];
                    break;
                }
            }
            sort(nums.begin() + p + 1, nums.end());
        }
    }
};