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
从数组尾部开始向前数,如果一直都是increasing order的话,那么就没有更大的permutation。如果遇到了一个违反increasing order的数,那么就有更大的permutation。找到了这个数的index后,再从尾部开始向前找,找到第一个比violator更大的数(swap index)的index,然后交换这两个数。
比如3 6 4 2 1这个数组,violator就是3,swap index就是4.交换以后变成4 6 3 2 1。最后再把violator index右边的所有数字反序,即本来是升序排列的变成降序排列。最后结果就是4 1 2 3 6.
public class Solution {
public void nextPermutation(int[] num) {
if(num.length < 2)
return;
//find the index of the first number that violates increasing order
int notIncreasingIndex = num.length - 2;
while(notIncreasingIndex >= 0){
if(num[notIncreasingIndex] < num[notIncreasingIndex + 1]){
break;
}
notIncreasingIndex--;
}
//find the first index that is bigger than the not-increasing index
if(notIncreasingIndex >= 0){
int swapIndex = num.length - 1;
while(num[swapIndex] <= num[notIncreasingIndex] && swapIndex > notIncreasingIndex){
swapIndex--;
}
swap(num, swapIndex, notIncreasingIndex);
}
//reverse all elements to the right of the not-increasing index
notIncreasingIndex++;
int end = num.length - 1;
while(end > notIncreasingIndex){
swap(num, end, notIncreasingIndex);
end--;
notIncreasingIndex++;
}
}
public void swap(int[] num, int i, int j){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
本文介绍了一个算法问题——寻找数组中字典序的下一个更大排列。文章详细解释了算法思路,并提供了一个Java实现示例,包括如何查找违反递增顺序的元素并进行相应的交换和反转操作。

被折叠的 条评论
为什么被折叠?



