51 - 上一个排列

2017.9.25

可以理解为下一个排列的逆思路。

下一个排列,是将一个升序序列逐步调整为降序序列的过程。

上一个排列,可以理解为将一个降序序列逐步调整为升序序列的过程。

这样,首先就是从后向前遍历找到 num[flag]>num[flag+1]

然后再从后向前遍历,找到比num[flag]小的最大值。交换位置后,排序。注意这里的排序应该是降序的。

public class Solution {
    /*
     * @param nums: A list of integers
     * @return: A list of integers that's previous permuation
     */
    	public List<Integer> previousPermuation(List<Integer> nums) {
        // write your code here
		int size = nums.size();
		if(size <= 1){
			return nums;
		}
		int flag = size-2;
		Integer []num = new Integer[size];
		num = nums.toArray(num);
		// 从后向前遍历,找到num[flag] > num[flag + 1];记录flag的位置
		while(flag >= 0){
			if(num[flag] > num[flag+1]){
				break;
			}
			flag--;
		}
	    if(flag < 0){
			Arrays.sort(num);
			List<Integer> res = new LinkedList<>();
			for(int i = num.length - 1;i>=0;i--){
				res.add(num[i]);
			}
			return res;
		}
		// 从后向前遍历,找到比num[flag]小的最大的数。
		int i = size - 1;
		while(i>= 0){
			if(num[i] < num[flag]){
				int tmp = num[flag];
				num[flag] = num[i];
				num[i] = tmp;
				break;
			}
			else{
				i--;
			}
		}
		Integer []arr_tmp = new Integer[size - flag]; 
		arr_tmp = Arrays.copyOfRange(num, flag+1, size);
		arr_tmp = turnList(arr_tmp);
		for(int h = flag+1;h<size;h++){
			num[h] = arr_tmp[h-flag-1];
		}
		return arrToList(num);
    }
	public List<Integer> arrToList(Integer []nums){
		List<Integer> res = new LinkedList<Integer>();
		int size = nums.length;
		for(int i = 0; i < size; i++){
			res.add(nums[i]);
		}
		return res;
	}
	public Integer[] turnList(Integer []nums){
		int size = nums.length;
		if(size <= 1){
			return nums;
		}
		Arrays.sort(nums);
		Integer []res = new Integer[size];
		for(int i = 0; i< size; i++){
			res[i] = nums[size-i-1];
		}
		return res;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值