leetcode之八Next Permutation

copyright:leetcode

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

public class Solution {
    public void nextPermutation(int[] num) {
		boolean isDone = false;
		int[] nearest = new int[2];//nearest[0] for value, nearest[1] for index
		if(num.length != 1){
			//find inverted sequence
			for(int i=num.length-2;i >= 0;i--){
				//number 10 is never acheved by subtraction between 2 numbers 
				nearest[0] = Integer.MAX_VALUE;
				nearest[1] = -1;
				for(int j = i+1;j < num.length ;j++){
					if(num[i] < num[j] && nearest[0] > (num[j] - num[i])){
						//find number nearest num[i]
						nearest[0] = num[j] - num[i];
						nearest[1] = j;
					}
				}
				
				if(nearest[0] != Integer.MAX_VALUE){
					//swap	
					int tmp = num[i];
					num[i] = num[nearest[1]];
					num[nearest[1]] = tmp;
					//sort i+1 to num.length - 1
					Arrays.sort(num, i+1, num.length);
					
					isDone = true;
					break;
				
				}
			}
			int tmp;
			//if there is no inverted sequence,invert all of it
			if(isDone == false)
				for(int i=0;i < num.length / 2;i++){
					tmp = num[i];
					num[i] = num[num.length - 1 - i];
					num[num.length - 1 - i] = tmp;
				}
		}
		
    }
}

原理:外层递减扫描从num[]的倒数第2位开始,假设当前扫描位为x,开始查找所有逆序(x, y),将x与y(y满足min(y-x))交换,然后将x(不包括x)以后的序列按升序排列。








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值