Next Permutation(下一个排列)

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

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值