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
感觉属于那种数学找规律,然后把这个规律用程序表达,写的程序比较简单
找到i满足nums[i]<nums[i+1];
从{i-nums.length-1}中找到比nums[i]大且最小的,其余的按顺序排列
public void nextPermutation(int[] nums) {
if(nums.length<=1) return;
int i=nums.length-2;
for(;i>=0;i--){
if(nums[i]<nums[i+1]) break;
if(i==0){
Arrays.sort(nums);
return;
}
}
int first=nums[i];
int[] ends=Arrays.copyOfRange(nums,i,nums.length);
Arrays.sort(ends);
int j=0;
for(;j<ends.length;j++){
if(ends[j]>first) break;
}
nums[i]=ends[j];
i++;
for(int k=0;k<ends.length;k++){
if(j!=k){
nums[i]=ends[k];
i++;
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。