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
求全排列的下一个序列
结题思路:从后往前,找到第一个降序的位置n,将n之后的数字翻转,并将位置n-1的数字与之后的第一个比它大得出数字交换即可。
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
if(n < 2) {
return;
}
int right = n-1;
while(right > 0) {
if(nums[right -1] < nums[right]) {
break;
}
right--;
}
int l = right;
int r = n-1;
while(l < r) {
int temp = nums[l];
nums[l]=nums[r];
nums[r]= temp;
l++;
r--;
}
if(right == 0) {
return;
}
int next = nums[right - 1];
for(int i = right; i < n ; i++) {
if(nums[i] > next) {
nums[right - 1] = nums[i];
nums[i] = next;
break;
}
}
}
}```
本文介绍了一个算法,用于在原地将数组中的整数重新排列成字典序中更大的排列。如果不存在更大的排列,则将其重新排列为最小可能的顺序。文章详细解释了算法的实现过程,包括寻找第一个降序元素,翻转其后的所有元素,并与第一个大于当前元素的值进行交换。
9万+

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



