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
分析:
首先,我们观察到对于任何给定序列的降序,没有可能的下一个更大的排列。
我们需要从右边找到第一对两个连续的数字 a[i] 和 a[i−1],它们满足 a[i]>a[i-1]。现在,没有对 a[i-1]右侧的重新排列可以创建更大的排列,因为该子数组由数字按降序组成。因此,我们需要重新排列 a[i-1]右边的数字,包括它自己。
所以为了找到比当前序列大的下一个序列,我们可以先将a[i-1]后面的数进行倒置,因为原来就满足前一个大于后一个数,所以转置后得到从小到大顺序。这个时候再去在里面找比a[i-1]大的最小的数,进行互换。
class Solution {
public void nextPermutation(int[] nums) {
int len=nums.length;
//数组长度至少为二
if(len>=2){
int i=len-1;
//从右边寻找第一组两个连在一起左右的数满足左边小于右边的数
for(i=len-1;i>0;i--){
if(nums[i]>nums[i-1]){
//将其变为从小到大
reverse(nums,i,len-1);
int j=i;
int temp=0;
//寻找i-1后面比nums[i-1]大的最小的数
for(j=i;j<len;j++){
if(nums[j]>nums[i-1]){
temp=nums[j];
break;
}
}
nums[j]=nums[i-1];
nums[i-1]=temp;
break;
}
if(nums[i]<=nums[i-1])
continue;
}
//表示数组是从大到小的形式,直接转置
if(i==0){
reverse(nums,0,len-1);
}
}
}
/*
对数组固定部分进行转置
**/
private void reverse(int[] nums,int start,int end){
int temp=0;
int len=(end-start+1)/2;
for(int i=start,j=end;i<len+start;i++){
temp=nums[i];
nums[i]=nums[j];
nums[j--]=temp;
}
}
}