- Previous Permutation
中文English
Given a list of integers, which denote a permutation.
Find the previous permutation in ascending order.
Example
Example 1:
Input:[1]
Output:[1]
Example 2:
Input:[1,3,2,3]
Output:[1,2,3,3]
Example 3:
Input:[1,2,3,4]
Output:[4,3,2,1]
Notice
The list may contains duplicate integers.
解法1:思路跟Next Permutation很相似,只是刚好反过来而已。
以A={3,1,2}为例,
先从后往前遍历,找到第一个index使得A[i]<A[i - 1]。这里我们找到index=1,因为1<3。然后我们再从后往前遍历,找到第一个i使得A[i]<A[index-1]。这里我们找到i=2,因为A[2]=2<3。然后我们把A[i]和A[index-1]对调,再将A[index…n-1]反排序即可。上面对调后有result={2,1,3},反排序后得{2,3,1}即为结果。
代码如下:
class Solution {
public:
/*
* @param nums: A list of integers
* @return: A list of integers that's previous permuation
*/
vector<int> previousPermuation(vector<int> &nums) {
int n = nums.size();
if (n <= 1) return nums;
vector<int> results = nums;
int index = 0;
for (int i = n - 1; i > 0; --i) {
if (nums[i] < nums[i - 1]) {
index = i;
break;
}
}
if (index == 0) {
reverse(results.begin(), results.end());
return results;
}
for (int i = n - 1; i > 0; --i) {
if (nums[i] < nums[index - 1]) {
swap(results[i], results[index - 1]);
sort(results.begin() + index, results.end());
reverse(results.begin() + index, results.end());
break;
}
}
return results;
}
};