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 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

 

分析:

首先,我们观察到对于任何给定序列的降序,没有可能的下一个更大的排列。

我们需要从右边找到第一对两个连续的数字 a[i] 和 a[i−1],它们满足 a[i]>a[i-1]。现在,没有对 a[i-1]右侧的重新排列可以创建更大的排列,因为该子数组由数字按降序组成。因此,我们需要重新排列 a[i-1]右边的数字,包括它自己。

所以为了找到比当前序列大的下一个序列,我们可以先将a[i-1]后面的数进行倒置,因为原来就满足前一个大于后一个数,所以转置后得到从小到大顺序。这个时候再去在里面找比a[i-1]大的最小的数,进行互换。

Next Permutation

class Solution {
    public void nextPermutation(int[] nums) {
        int len=nums.length;
         
        //数组长度至少为二
        if(len>=2){
            int i=len-1;
        
            //从右边寻找第一组两个连在一起左右的数满足左边小于右边的数
            for(i=len-1;i>0;i--){
                
                if(nums[i]>nums[i-1]){
                    
                    //将其变为从小到大
                    reverse(nums,i,len-1);
                    
                    int j=i;
                    int temp=0;
                    
                    //寻找i-1后面比nums[i-1]大的最小的数
                    for(j=i;j<len;j++){
                        if(nums[j]>nums[i-1]){
                            temp=nums[j];
                            break;
                        }
                    }
                    
                    nums[j]=nums[i-1];
                    nums[i-1]=temp;
                    
                    break;
                }

                if(nums[i]<=nums[i-1])
                    continue;
            }
            
            //表示数组是从大到小的形式,直接转置
            if(i==0){
                reverse(nums,0,len-1);
            }
        
        }
    }
    
/*
对数组固定部分进行转置
**/
    private void reverse(int[] nums,int start,int end){
        
        int temp=0;
        int len=(end-start+1)/2;
        
        for(int i=start,j=end;i<len+start;i++){
            temp=nums[i];
            nums[i]=nums[j];
            nums[j--]=temp;
            
        }
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值