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

代碼:

class Solution {
public:
    void sort(vector<int>& nums, int index){
        for(int i = index + 2; i < nums.size(); i++){
            for(int j = index + 1; j < i; j++){
                if(nums[i] < nums[j]){
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                }
            }
        }
    }
    void nextPermutation(vector<int>& nums) {
        int index = -1;
        for(int i = nums.size() - 2; i >= 0; i--){
            bool flag = false;
            for(int j = nums.size() - 1; j > i; j--){
                if(nums[i] < nums[j]){
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                    index = i;
                    flag = true;
                    break;
                }
            }
            if(flag) break;
        }
        sort(nums, index);
    }
};

 31題,Medium,三次AC,不要問我爲什麼沒有按順序寫題,因爲我也不知道哈哈,反正基本順序差不多,看哪個順眼做哪個。今天又是腦殼疼的一天。上午看了一上午論文,論文的一個算法看了好幾天了看不懂,難受,什麼時候能徹徹底底愉愉快快開開心心無憂無慮地敲代碼啊。I like watching my fingers dancing on the keybord。哈哈哈,很裝逼有木有。

題目要求,已知一個數組的排列,重新排列該數組爲下一個排列。我的思路:

從數組最右端開始遍歷,找該數右邊從右數第一個大於它的數,進行交換。(MD好像有點拗口,GRD論文更拗口,還是英文的)。如果找到的話,記錄一下該數的位置,index。最後將數組的index到結束的數字按照從小到大的順序排列。sort函數是簡單的插入排序(快排寫一次忘一次也是難受的不行T.T)。簡而言之就是你要想這個數字稍微大一點,那肯定是優先從個位數開始讓他變大,否則它就不是大“一點”了。而且由於數組所有元素是不變的,也就是隻能交換數字。那肯定是讓該數字和它右邊的比他大的數字的最小值進行交換,就行了。拗口拗口,不管了,意會吧。債見,滾去看論文了T.T

靜心盡力!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章