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

解题思路,从后向前循环,直到找到前一个数比后一个数小的时候,即a(i-1)< a(i),然后将a(i),a(i+1)…a(n-1)中比a(i)大得最少的数找出来,互换位置,然后将后面的数倒序即可。

如2,4,3,2
当i=1时a(0)< a(1),找到3比2大,将第一个2和3互换位置成3,4,2,2。然后将后面的4,2,2倒序即成3,2,2,4。

代码如下:

public void nextPermutation(int[] nums) {
    int n=nums.length;
    int i=n-1;
    while(i>0){
        if(nums[i-1]>=nums[i]){
            i--;
        }else{
            int j=n-1;
            while(j>=i&&nums[j]<=nums[i-1]){
                j--;
            }
            int temp=nums[i-1];
            nums[i-1]=nums[j];
            nums[j]=temp;
            reverseArrayFromIndex(nums, i);
            return ;
        }
    }
    reverseArrayFromIndex(nums, 0);
}   

public void reverseArrayFromIndex(int[] nums,int start){
    int low=start,high=nums.length-1;
    int temp=0;
    while(low<high){
        temp=nums[low];
        nums[low++]=nums[high];
        nums[high--]=temp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值