LeetCode31: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, 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,2
3,2,11,2,3
1,1,51,5,1

基本思想:數組

  1. 使用一個指針從數組尾端開始遍歷,找到第一個這種元素,它的前一個元素小於這個元素。
  2. 假設數組中不存在這種元素。那麼數組最開始是降序排列的。將數組進行升序排列就能夠。

  3. 假設找到了這種元素。比方數組爲[1,3,2,0],那麼此時指針iter是指向3的,它的前一個元素是1,那麼需要前一個指針與它後面元素中大於1且最小的元素交換,這兒就是將1與[3,2,0]中最小的元素交換。因此1應該和2交換,而後再將剩下的元素進行升序排序就能夠。

這兒由於數組是反向遍歷的,因此可以使用使用stl中的反向迭代器。markdown


runtime:12msui

class Solution {
public:
    void nextPermutation(vector<int>& nums) {

        if(nums.size()<2) return ;
        auto iter=nums.rbegin();
        while(iter!=(nums.rend()-1)&&*iter<=*(iter+1))
            iter++;

        if(iter==nums.rend()-1)
            sort(nums.begin(),nums.end());
        else
        {
            auto upper=iter;
            auto tmp=nums.rbegin();
            for(;tmp!=iter;tmp++)
            {
                if(*tmp>*(iter+1))
                {
                    if(*tmp<*upper)
                    {
                        upper=tmp;
                    }
                }
            }
            swap(*(iter+1),*upper);

            sort(nums.rbegin(),iter+1,greater<int>());
        }

    }
};
相關文章
相關標籤/搜索