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
题目分析:求下一排列,参考C++ STL的next_permutation()的实现方法
数据有偏向性,当前击败96.81%,用注释的代码只能击败20+%
public class Solution {
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public void nextPermutation(int[] nums) {
int n = nums.length;
if (n < 2) {
return;
}
int pos1 = -1, pos2 = 0;
for (int i = 1; i < n; i ++) {
if (nums[i] > nums[i - 1]) {
pos1 = i;
}
}
// for (int i = n - 1; i > 0; i --) {
// if (nums[i] > nums[i - 1]) {
// pos1 = i;
// break;
// }
// }
if (pos1 == -1) {
Arrays.sort(nums);
return;
}
for (int i = n - 1; i >= pos1 - 1; i --) {
if (nums[i] > nums[pos1 - 1]) {
pos2 = i;
break;
}
}
swap(nums, pos1 - 1, pos2);
Arrays.sort(nums, pos1, n);
}
}