LeetCode OJ算法题(三十):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

解法:

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

观察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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值