https://leetcode.com/problems/next-permutation/
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
这道题主要还是数学操作,算法的解释见这里:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html
如果要last permutation,算法也差不多,只是大小反过来就行
另外,在第二步,找一个数组中比给定值大的最小值时,可以用binary search来做,因为此时需要找的范围是sorted的,这里就不实现了。
代码如下:
public class Solution {
public void nextPermutation(int[] num) {
int i= num.length-2;
while(i>=0 && num[i]>=num[i+1]){
i--;
}
if(i<0){
reverse(num, 0, num.length-1);
return;
}
else{
int j=num.length-1;
while(j>i && num[j]<=num[i]){
j--;
}
swap(num, i, j);
reverse(num, i+1, num.length-1);
}
}
public void swap(int[] num, int i, int j){
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
public void reverse(int[] num, int start, int end){
while(start<end){
swap(num, start, end);
start++;
end--;
}
return;
}
}