题目描述 31. Next Permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3]
, the following are all the permutations of arr: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
.
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
For example, the next permutation of arr = [1,2,3] is [1,3,2]
.
Similarly, the next permutation of arr = [2,3,1] is [3,1,2]
.
While the next permutation of arr = [3,2,1]
is [1,2,3]
because [3,2,1]
does not have a lexicographical larger rearrangement.
Given an array of integers nums, find the next permutation of nums.
The replacement must be in place and use only constant extra memory.
给定一个整数数组,找到它的下一个排列。下一个排列是指将数组中的元素重新排列成字典序中下一个更大的排列。如果不存在下一个更大的排列,则将数组重新排列为字典序最小的排列(即升序排列)。
解题思路
- 从数组的末尾开始,找到第一个不满足递增关系的元素
nums[i]
,即nums[i]
<nums[i+1]
。 - 如果找不到这样的
i
,说明数组已经是最大的排列,直接反转数组即可。 - 如果找到了
i
,再从数组的末尾开始,找到第一个大于nums[i]
的元素nums[j]
。 - 交换
nums[i]
和nums[j]
。 - 最后将
i
之后的元素反转,得到下一个排列。
步骤详解
- 步骤 1:从后向前找到第一个不满足递增关系的元素
nums[i]
。 - 步骤 2:从后向前找到第一个大于
nums[i]
的元素nums[j]
。 - 步骤 3:交换
nums[i]
和nums[j]
。 - 步骤 4:将
i
之后的元素反转。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
int i = n - 2;
// 步骤 1:找到第一个不满足递增关系的元素
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = n - 1;
// 步骤 2:找到第一个大于 nums[i] 的元素
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
// 步骤 3:交换 nums[i] 和 nums[j]
swap(nums[i], nums[j]);
}
// 步骤 4:反转 i 之后的元素
reverse(nums.begin() + i + 1, nums.end());
}
};
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
let n = nums.length;
let i = n - 2;
// 步骤 1:找到第一个不满足递增关系的元素
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
let j = n - 1;
// 步骤 2:找到第一个大于 nums[i] 的元素
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
// 步骤 3:交换 nums[i] 和 nums[j]
[nums[i], nums[j]] = [nums[j], nums[i]];
}
// 步骤 4:反转 i 之后的元素
let left = i + 1, right = n - 1;
while (left < right) {
[nums[left], nums[right]] = [nums[right], nums[left]];
left++;
right--;
}
};