題目描述:
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Notice
The list may contains duplicate integers.
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]
這題注意到,正常的規律從後到前應該是後一個數比前一個數大。如果發現前一個數更小時,這就是發生轉折點的地方。首先,我們先找到這個轉折點(如果找不到,那麼答案就是reversed array);然後從轉折點往後看,找出大於轉折點的最小數,並把這個數和轉折點互換。對於新轉折點後那些剩下的數,做一個sort。這樣,改完的數組就是答案了。
Mycode(AC = 32ms):
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 the key position
int idx = -1;
for (int i = nums.size() - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
idx = i;
break;
}
}
// if is the larget sequence, return reverse
if (idx == -1) {
reverse(nums.begin(), nums.end());
return nums;
}
int second_min = nums[idx + 1], second_idx = idx + 1;
for (int i = idx + 1; i < nums.size(); i++) {
if (nums[i] > nums[idx] && nums[i] < second_min) {
second_min = nums[i];
second_idx = i;
}
}
// swap
swap(nums, idx, second_idx);
// sort the rest numbers
sort(nums.begin() + idx + 1, nums.end());
return nums;
}
void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};