Question:
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Example
For [1,3,2,3]
, the next permutation is [1,3,3,2]
For [4,3,2,1]
, the next permutation is [1,2,3,4]
Note
The list may contains duplicate integers.
What is Next Permutation?
The permutation with current charactors that is lexicographically next.
1234 -> 1243
4321 -> 1234
1243 -> 1324
2134 -> 2143
Idea:
Answer:
class Solution { public: /** * @param nums: An array of integers * @return: An array of integers that‘s next permuation */ vector<int> nextPermutation(vector<int> &nums) { // write your code here if (nums.size() <= 1) { return nums; } //find first element that is smaller that next element int first_small_index = -1; for (int i = nums.size() - 2; i >= 0; --i) { if (nums[i] < nums[i+1]) { first_small_index = i; break; } } //find the first element that is just bigger than the element we found if (first_small_index != -1) { int first_bigger_index = first_small_index; for (int i = first_small_index + 1; i < nums.size(); ++i) { if (nums[i] > nums[first_small_index]) { first_bigger_index = i; } else { break; } } swap(nums[first_small_index], nums[first_bigger_index]); } // Reverse rest array reverse(nums.begin() + first_small_index + 1, nums.end()); return nums; } };
时间: 2024-09-29 02:03:21