题目描述:
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
思路解析:
- 从后往前寻找不是递增的下标i,
- 然后从i 往后找到比下标i 对应的数字大的
- 然后把从i+1到最后一个互相交换
- 从后往前遍历数组,如果一直是逐渐增大的,则已经是最大的了,如果出现了一个下降的数,那么遍历就到此为止,因为这已遍历的部分就可以排列成下一个较大的数了
- 当找到这个突然下降的点A后,由于它后面已经排列为“最大”,即从前往后一直变小,所以应该从后面比A大的数中找最小的点B,然后A和B交换位置。这个时候以B开头,后面也是最大的排列,由于需要找下一个较大的数,应该把B后面的排列改为最小的,只需要将后面的数组顺序逆转一下即可。如果一直没有找到下降的点,则全部逆转即可。
- https://blog.youkuaiyun.com/u012848330/article/details/52090111
代码:
public class Solution {
public void nextPermutation(int[] num) {
if(num==null||num.length==0)
return ;
int i=num.length-2;
while(i>=0&&num[i]>=num[i+1])
i--;
if(i>=0){
int j=i+1;
while(j<num.length&&num[j]>num[i])
j++;
j--;
swap(num,i,j);
}
reverse(num,i+1,num.length-1);
}
public void swap(int[] num,int i,int j){
int temp = num[i];
num[i]=num[j];
num[j]=temp;
}
public void reverse(int[] num,int i,int j){
while(i<j)
swap(num,i++,j--);
}
}