1. Question
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, do not allocate 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
2. Solution
从后往前,找第一个下降的数字nums[i] > nums[i - 1],如果没找到那么直接将数组反转即可。
再从后往前,找一个数nums[j] > nums[i - 1],交换他们两个数字,然后再将nums[i - 1]之后的数进行反转。
时间复杂度O(n)。
3. Code
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i = nums.size() - 1;
for (; i > 0; i--) { // 找第一个下降的位置
if (nums[i] > nums[i - 1])
break;
}
if (i == -1 || i == 0) {
reverse(nums.begin(), nums.end());
} else {
for (int j = nums.size() - 1; j >= 0; j--) {
if (nums[j] > nums[i - 1]) { // 找第一个比下降位置数大的
swap(nums[j], nums[i - 1]);
reverse(nums.begin() + i, nums.end()); // 反转之后的数
break;
}
}
}
}
};