- Next Permutation II
中文English
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).
Example
Example 1:
Input:1,2,3
Output:1,3,2
Example 2:
Input:3,2,1
Output:1,2,3
Example 3:
Input:1,1,5
Output:1,5,1
Challenge
The replacement must be in-place, do not allocate extra memory.
解法1:从后往前找,直到找到一个nums[i]>nums[i-1]。然后再从后往前找,找到第一个大于nums[i-1]的数nums[j]。然后swap(nums[i-1], nums[j]),然后reverse nums[i…n-1]。
注意:
- 如果i=0,说明整个数组为降序序列,如[3,2,1],此时reverse整个字符串即可。
代码如下:
class Solution {
public:
/**
* @param nums: An array of integers
* @return: nothing
*/
void nextPermutation(vector<int> &nums) {
int n = nums.size();
if (n <= 1) return;
int i = 0, j = 0;
for (i = n - 1; i > 0; --i) {
if (nums[i] > nums[i - 1]) break;
}
if (i == 0) {
reverse(nums.begin(), nums.end());
return;
}
for (j = n - 1; j > i; --j) {
if (nums[j] > nums[i - 1]) break;
}
swap(nums[i - 1], nums[j]);
reverse(nums.begin() + i, nums.end());
// int p1 = i, p2 = n - 1;
// while(p1 < p2) {
// swap(nums[p1], nums[p2]);
// p1++; p2--;
// }
}
};
博客围绕 Next Permutation II 问题展开,要将数字重排成字典序中下一个更大排列,若无法实现则排成最小排列。给出多个示例,还提出原地替换、不额外分配内存的挑战,并介绍了从后往前查找、交换和反转的解法,若数组为降序则反转整个数组。

被折叠的 条评论
为什么被折叠?



