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;
}
}
}
}```