您的位置:首页 > 其它

LeetCode OJ算法题(三十):Next Permutation

2014-07-24 21:29 281 查看
题目:

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

解法:
题目要求用数组中的数,生成一个最小的更大的排列出来,大小按照字典排序。如果没有更大的排列了,就生成最小的排列

观察1,3,2,4,1,要使排列变大,就需要把后面大的数字调整到前面,可以发现要使排列增量最小,高位的数字就不能动,找到最低的需要调整的数字

基本思想是找到最后一个极大值,他前面的一位,即为i,就是应该调整位置,将A[i]之后大于A[i]的最小值与A[I]交换,并对包含A[i+1]之后的元素排序即可。

public class No30_NextPermutation {
public static void main(String[] args){
int[] num = new int[]{1};
nextPermutation(num);
//		quickSort(num, 0, num.length-1);
for(int k:num)
System.out.println(k);
}
public static void nextPermutation(int[] num) {
int index = 0;
for(int i=1;i<num.length;i++){
if(num[i]>num[i-1]){
index = i;
}
}
if(index != 0){
int i = index;
while(i< num.length && num[i] > num[index-1]) i++;
num[index-1] += num[i-1];
num[i-1] = num[index-1] - num[i-1];
num[index-1] = num[index-1] - num[i-1];
}
quickSort(num, index, num.length-1);
}
public static void quickSort(int[] array, int i, int j){
if(i<j){
int mid = partition(array, i, j);
quickSort(array, i, mid-1);
quickSort(array, mid+1, j);
}
}
public static int partition(int[] array, int i, int j){
int pivot = array[i];
while(i<j){
while(i<j && array[j] >= pivot) j--;
array[i] = array[j];
while(i<j && array[i] <= pivot) i++;
array[j] = array[i];
}
array[i] = pivot;
return i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法