LeetCode 31. Next Permutation

Description: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
2,3,1 → 3,1,2

思路:按照字典從小到大排序,求當前排列的下一個更大(這是重點)的排列,如果已經是最大排列,則下一個排列是最小排列。理解了這2層意思,就很好寫了。數組中的數字從左往右級別依此降低,所以遍歷從右邊開始,共2層遍歷,第一層遍歷的是要替換的數字numL,第二層遍歷numL右邊的數字numR,比較numR>numL,true則替換,然後在給numL(替換後是numR)右邊的數字排序,確保是下一個更大的排列。

參考代碼:

void MySolution::nextPermutation(vector<int>& nums) {
    int len = nums.size();
    for (int i = len-2; i >= 0; i--) {
        for (int j = len-1; j > i; j--) {
            if (nums[j] > nums[i]) {
                int temp = nums[j];
                nums[j] = nums[i];
                nums[i] = temp;
                sort(nums.begin() + i + 1, nums.end());
                return;
            }
        }
    }
    reverse(nums.begin(), nums.end());
}

測試結果:
Runtime: 8 ms, faster than 78.21% of C++ online submissions for Next Permutation.
Memory Usage: 8.6 MB, less than 94.62% of C++ online submissions for Next Permutation.

發佈了65 篇原創文章 · 獲贊 75 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章