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,1public class Solution {
public void nextPermutation(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
int sz=num.length;
if(sz<=1) return;
int i=sz-1;
while(i>0) {
if(num[i-1]<num[i]) {
break;
}
i--;
}
quickSort(num,i,sz-1);
if(i==0) return;
int j=i-1;
while(num[j]>=num[i])i++;
swap(num,j,i);
}
private void swap(int[] num, int x, int y) {
num[x] = num[x]^num[y];
num[y] = num[x]^num[y];
num[x] = num[x]^num[y];
}
private void quickSort(int[] num, int x, int y) {
if(x>=y) return;
int q = partition(num,x,y);
quickSort(num,x,q-1);
quickSort(num,q+1,y);
}
private int partition(int[] num, int p, int r) {
int pivot = num[r];
int i=p-1;
for(int j=p ; j<r-1; j++) {
if(num[j]<=pivot) {
i++;
swap(num, i, j);
}
}
swap(num, i+1, r);
return i+1;
}
}
本文介绍了一种名为NextPermutation的算法实现,该算法能够就地重排数组元素,形成字典序上的下一个更大排列。如果无法形成更大的排列,则将数组重排为最小可能的顺序(即升序)。文章提供了完整的Java代码示例,并通过几个实例演示了其工作原理。
153

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



