题目描述:
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Notice
The list may contains duplicate integers.
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]
这题注意到,正常的规律从后到前应该是后一个数比前一个数大。如果发现前一个数更小时,这就是发生转折点的地方。首先,我们先找到这个转折点(如果找不到,那么答案就是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;
}
};