Leetcode -- 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, 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,1


思路:這道題還是有點難度的,參考了別人的思路,解法如下:

6,8,7,4,3,2爲例:
這裏寫圖片描述

  1. 首先從後往前遍歷,找到第一個不按遞增排列的元素,即nums[i-1],上圖中的6。
  2. 再從後往前,找到第一個比nums[i-1] 大的元素,即nums[j] , 上圖中的7。
  3. 交換nums[i-1]nums[j] 的位置,變成7, 8, 6, 4, 3, 2
  4. i → nums.size()-1 的元素進行排序, 變成:7, 2, 3, 4, 6, 8

C++代碼如下:

void nextPermutation(vector<int>& nums) {
        if (nums.size() <= 1)
            return;
        int right = nums.size() - 1;
        int i = right,j = right,temp;

        while (nums[i] <= nums[i - 1]) {
            --i;
        }
        if (i == 0) {
            sort(nums.begin(), nums.end());
            return;
        }


        while (nums[i-1] >= nums[j])
        {
            --j;
        }

        temp = nums[j];
        nums[j] = nums[i-1];
        nums[i-1] = temp;

        sort(nums.begin() + i,nums.end());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章