Leetcode 31 Next Permutation

HowieLee59發表於2018-10-28

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

這個題的意思是找到下一個最大的排列數,方法類似於雙指標,從後往前掃,當遇到可以進行更換的數的時候進行更換,並使用reverse進行反轉後面的數,使得後面的數為最小的。

1)

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.size() <= 1){
            return ;
        }
        int i = nums.size() - 1;
        while(i > 0 && nums[i] <= nums[i - 1]){
            --i;
        }
        if(i == 0){
            reverse(nums.begin(),nums.end());
        }else{
            int j = nums.size() - 1;
            while(nums[j] <= nums[i - 1]){
                --j;
            }
            swap(nums[j],nums[i - 1]);
            reverse(nums.begin() + i , nums.end());
        }
    }
};

2)

static const auto _______ = [](){//大概是一種特殊的讀取數的形式
    std::cout.sync_with_stdio(false);
    cin.tie(0);
    return 0;
}();
class Solution {
public:
    void nextPermutation(vector<int>& a) {
        int n=a.size();    
        int i;
        for(i=n-1;i>0;i--) {
            if(a[i]>a[i-1])   {
                int k=i;
                for(int j=i;j<n;j++) {
                    if(a[j]>a[i-1]&&a[j]<a[k])
                        k=j;
                }
                swap(a[i-1],a[k]);
                break;
            }
        }
        sort(a.begin()+i,a.end());
    }
};

 

相關文章