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
public static void nextPermutation(int[] nums) {
if(nums==null)
return;
int length=nums.length;
if(length==0||length==1)
return;
int flag=-1;
for(int i=length-2;i>=0;i--){
if(nums[i]<nums[i+1]){
flag=i;
break;
}
}
if(flag>-1){
int flag2=findBigger(nums,flag+1,length-1,nums[flag]);
exchange(nums,flag,flag2);
}
int left = flag>-1?flag+1:0;
int right = length-1;
while(right>left){
exchange(nums,right,left);
right--;
left++;
}
}
public static void exchange(int nums[],int a,int b){
int temp=nums[a];
nums[a]=nums[b];
nums[b]=temp;
}
public static int findBigger(int[] nums,int left,int right,int target){
//二分法
int middle = (left+right)/2;
if(target==nums[middle])
return middle-1;
if(middle==left)
return nums[right]>target?right:left;
if(target>nums[middle])
right=middle;
else if(target<nums[middle])
left=middle;
return findBigger(nums,left,right,target);
}