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 class Solution {
public void nextPermutation(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
for(int i=num.length-1; i>0; i--){
// find the place to increase next permutation
if(num[i-1]<num[i]){
// find the min value in num[i to end] that >num[i-1]
int j=i;
while(j<num.length && num[j]>num[i-1])
j++;
j--;
// swap them
int tmp = num[j];
num[j] = num[i-1];
num[i-1] = tmp;
// sort num[i to end]
Arrays.sort(num, i, num.length);
return;
}
}
// descending sorted, change it to ascending sorted
Arrays.sort(num);
return;
}
}