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
这道题有点进步,至少知道提交之前多跑几个自己尝试的test case, 然后test case还是设计不全面,导致了一次错误提交。再有一个问题就是,写代码之前,逻辑没有想太明白,以至于有逻辑错误在里面。
Arrays.sort(nums, start, end+1) 这个排序函数可以用来排序subarray, 挺好用的,希望能记住。
class Solution {
public void nextPermutation(int[] nums) {
if (nums == null || nums.length == 0) return;
int i = nums.length - 1;
while(i > 0){
if (nums[i] > nums[i-1]){
break;
}
else{
i--;
}
}
if (i > 0){
int min = Integer.MAX_VALUE;
int min_index = 0;
for(int j = i; j < nums.length; j++){
if (nums[j] > nums[i-1] && nums[j] < min){
min = nums[j];
min_index = j;
}
}
int tmp = nums[i-1];
nums[i-1] = nums[min_index];
nums[min_index] = tmp;
}
Arrays.sort(nums, i, nums.length);
return;
}
}
年龄大了开始听陈绮贞了,哎,神奇。