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
思路:本题意思就是找到比该数组表示的数刚刚大的数;从右往左逐渐遍历,直到找到后面的序列不是递减序列;然后将递减序列的每个值与当前找到的非递减序列的临界大的值,交换,并将原始的递减序列翻转就是最后的值。
以142543为例,后面的543是递减序列,加上2之后就不是了,然后从3往前找比2大的值,就是3,交换3和2143542,3后面的542是递减序列,由于3比2大,因此其后面紧接着的序列应该是最小的,故将542翻转后得到的245就是最小的值,这样便完成了。
时间复杂度:O(N)
空间复杂度:O(1)
public void nextPermutation(int[] nums) {
int len=nums.length;
int i;
for(i=len-1;i>0;i--){
if(nums[i]>nums[i-1])
break;
}
int temp;
if(i==0){
for(int p1=0,p2=len-1;p1<p2;p1++,p2--){
temp=nums[p1];
nums[p1]=nums[p2];
nums[p2]=temp;
}
return;
}
int j;
for(j=len-1;j>=i;j--){
if(nums[j]>nums[i-1])
break;
}
temp=nums[i-1];
nums[i-1]=nums[j];
nums[j]=temp;
for(int p1=i,p2=len-1;p1<p2;p1++,p2--){
temp=nums[p1];
nums[p1]=nums[p2];
nums[p2]=temp;
}
}
fddefdf