LeetCode——Next Permutation

本文详细介绍了一个高效的算法,用于实现数字序列的下一个字典序排列。该算法首先从序列末尾开始寻找第一个升序对,然后交换该对中的元素与后面序列中刚大于前者的最小元素,并对后续部分进行升序排序。此方法不仅能在原地修改输入数组,而且仅使用常数级额外内存,实测运行速度优于98.10%的在线提交。

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 and use only constant 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

如何得到下一个排列参见(http://www.cnblogs.com/grandyang/p/4428207.html)

解法

总体思路就是从后往前找,当第i+1个位大于第i位时,则要把第i位和其后面的数字中最小的一个大于它的数交换位置,然后将i+位之后的数从小到大排序

public void nextPermutation(int[] nums) {
        int n=nums.length;
        for( int i=n-2;i>=0;i--){
        	if(nums[i+1]>nums[i])
        	{
        		for(int j=n-1;j>i;j--){
        			if(nums[j]>nums[i])
        			{
        				int tmp=nums[j];
        				nums[j]=nums[i];
        				nums[i]=tmp;
        				Arrays.sort(nums, i+1, n);
        				return ;
        			}
        		}
        	}
        }
        Arrays.sort(nums);
    }

Runtime: 7 ms, faster than 98.10% of Java online submissions for Next Permutation.
Memory Usage: 38.7 MB, less than 27.52% of Java online submissions for Next Permutation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值