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
思路:
1.首先从尾部找到递增的断点i;
2.从i回过去找到最后一个比i小的点j
3.交换连i j 的元素
4.递增排序i后面的元素
class Solution {
public void nextPermutation(int[] nums) {
int length = nums.length;
for (int i = length - 2; i >= 0; i--) {
int in_index = -1;
int swap_index = -1;
//找到减少 i
if (nums[i] < nums[i + 1]) {
in_index = i;//递增点坐标
for (int j = i + 1;j < length; j++) {
//找到减少点i 小的数
if (nums[j] > nums[in_index]) {
swap_index = j;
}
}
}
if (in_index != -1 && swap_index != -1) {
//将两个坐标的数交换
int tmp = nums[in_index];
nums[in_index] = nums[swap_index];
nums[swap_index] = tmp;
//将后续的数组排序
Arrays.sort(nums, in_index + 1, length);
return;
}
}
Arrays.sort(nums);
}
}