问题描述
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 and use only constant 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
思路分析
给一个数组,表示一组数的排列,返回这组排列下一组比它大的排列。如果排列已经是从大到小的了,那就返回最初的从小到大的排列。
首先第一遍从后向前遍历数组,找到第一个nums[i] < nums[i+1]的i的位置,存为k。如果k不存在,reverse后返回。
然后第二次从后向前遍历数组,找到第一个大于nums[k]的least,交换两者的位置,将k之后的部分reverse就可以了。这样做能行的原因是,在第一次循环中找到的k,再换到least的位置之后,从k+1到nums.end()形成的正好是一个从大到小的排列,这时候将它reverse即可。因为least > k,形成的新数组就是下一个排列的形式。
代码
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int k = -1;
for (int i = nums.size() - 2; i >= 0; i--){
if (nums[i] < nums[i+1]){
k = i;
break;
}
}
if (k == -1){
reverse(nums.begin(), nums.end());
return;
}
int least = -1;
for (int i = nums.size() - 1; i >= 0; i--){
if (nums[i] > nums[k]){
least = i;
break;
}
}
swap(nums[k], nums[least]);
reverse(nums.begin() + k + 1, nums.end());
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
反思
很巧妙的算法,还可以处理重复的情况。