31 Next Permutation
Implementnext 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 bein-placeand 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,23,2,1→1,2,31,1,5→1,5,1
Solution)
class Solution {
public void nextPermutation(int[] nums) {
int pivot;
for(pivot=nums.length-1; pivot>0; pivot--)
if(nums[pivot] > nums[pivot-1]) break;
if(pivot != 0)
swap(nums, pivot-1);
inverse(nums, pivot);
return;
}
private void swap(int[] nums, int piv){
int j = nums.length-1;
while(j > piv)
if(nums[j--] > nums[piv]){
int tmp = nums[piv]; nums[piv] = nums[++j]; nums[j] = tmp; break;
}
return;
}
private void inverse(int[] nums, int piv){
int i = piv, j = nums.length-1;
while(i < j){
int tmp = nums[i]; nums[i++] = nums[j]; nums[j--] = tmp;
}
return;
}
}