LeetCode 【31. Next Permutation】

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.code

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).blog

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1it

 

這個最開始我比較不能理解題目的意思,後來才明白表示兩個排序之間沒有其餘的排序的意思是,好比1,2,3,4下一個排序是1,2,4,3 --> 1,3,2,4 --> 1,3,4,2 --> 1,4,2,3 -->.....io

就是說第二個排序組成的連續數字,比前面的大,而且中間沒有其餘的組合,若是已是4,3,2,1了,那麼下一個就是1,2,3,4即回到開頭。class

咱們來研究一下上面[1,2,3,4]的排序過程,好比比1,2,3,4大的是1,2,4,3怎麼出來的呢?再看看1,3,4,2 ---> 1,4,2,3 call

1.找到nums[i] > nums[i-1]next

2.找出i-nums.size()-1之間比nums[i-1]大的最小值,交換這個值與nums[i-1]sort

3.對i-1到nums.size()-1之間的元素進行排序di

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int end = nums.size()-1;
        while( end > 0 ){
            if( nums[end] > nums[end-1] ){
                break;
            }
            else{
                end--;
            }
        }
        if( end == 0 ){
            sort(nums.begin(),nums.end());
        }
        else{
            int min = nums[end];
            int index = end;
            for( int i = nums.size()-1; i > end; i-- ){
                if( nums[i] < min && nums[i] > nums[end-1] ){
                min = nums[i];
                index = i;
                }
            }
            swap(nums[index],nums[end-1]);
            sort(nums.begin()+end,nums.end());
        }
    }
};
相關文章
相關標籤/搜索