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

思路:先从右往左,找到第一个 a[k]<a[k+1] (即第一个破坏了从右到左的升序的元素位置),假如从右到左都是升序,那么下一个排列就是现在数列的翻转。找到这个 k 后,在这个位置的后面找一个 a[l]>a[k],并且 l 尽可能大的数(从右到左扫描,找到第一个 l,使得 a[l]>a[k]),交换 a[k]a[l],然后将 a[k+1,:] 进行翻转。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int sz=nums.size();
        int k=-1;
        for(int i=sz-2;i>=0;i--)
            if(nums[i]<nums[i+1]){
                k=i;
                break;
            }
        if(k==-1){
            reverse(nums.begin(),nums.end());
            return;
        }else{
            int l=-1;
            for(int i=sz-1;i>k;i--)
                if(nums[i]>nums[k]){
                    l=i;
                    break;
                }
            swap(nums[k],nums[l]);
            reverse(nums.begin()+k+1,nums.end());
        }
        return ;
    }
};
posted @ 2020-07-23 10:20  winechord  阅读(88)  评论(0编辑  收藏  举报