Next Permutation (Java)

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. 从后往前遍历,找到第一个非升序的,比如1,2,4,3 则找到了2,记录value和location。

2. 如果遍历完也没找到这个元素就证明这是排列的最后一个,那么从头到尾做置换,使其升序排列。比如4,3,2,1,变换为1,2,3,4

3. 如果步骤1找到了那个元素,则从后往前遍历到location的位置,找到第一个大于它的数值,比如1,2,4,3,从后向前找,找到了3,然后交换,即得到1,3,4,2

4. 将location后面的元素做交换,如1,3,4,2 将后面的4,2变换为2,4,得1,3,2,4


Source

public class Solution {
    public void nextPermutation(int[] num) {
        int len = num.length;
        int key = 0, i, temp, loc = 0;
        for(i = len - 1; i > 0; i--){
        	if(num[i - 1] < num[i]){
        		key = num[i - 1];
        		loc = i - 1;
        		break;
        	}
        }
        if(i == 0){
        	for(i = 0; i < len / 2; i++){
        		temp = num[i];
        		num[i] = num[len - i - 1];
        		num[len - i - 1] = temp;
        	}
        	return;
        }
    
        for(i = len - 1; i > loc; i--){
        	if(num[i] > key){
        	    temp = key;
        		num[loc] = num[i];
        		num[i] = temp;
        		break;
        	}
        }
   
        for(i = loc + 1; i < loc + 1 + (len - loc - 1) / 2; i++){
        	temp = num[i];
        	num[i] = num[len - 1 - i + loc + 1];
        	num[len - 1 - i + loc + 1] = temp;
        }
    }
}


Test

    public static void main(String[] args){
    	
    	int[] num = {4,3,2,1};

    	new Solution().nextPermutation(num);;
    	for(int i = 0; i < num.length; i++){
    		System.out.print(num[i] + " ");
    	}
    
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值