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


题意:给定一串数字,根据字典序求出下一个字符串;如果不存在下一个,则从小到大输出

思路:字典序排序的最终结果是字符从大到小排列,首先从后往前扫描,找到第一组i,j,使i<j&&num[i]<num[j]。如果不存在,则表示该串以排序完毕,则从小到大排序结束算法。否则,再从后往前扫描,找到第一个num[k]>num[i],两数交换。然后从j开始到字符串末尾进行反转,排序完毕,结束算法。

实现

public class Solution {
    public void nextPermutation(int[] num) {
        int l=num.length;
        boolean flag=false;
        for(int j=l-1,i=j-1;!flag&&i>=0;j--,i=j-1){//从右往左寻找是否存在i<j&&num[i]<num[j]
             if(num[i]<num[j]){//如果存在i<j&&num[i]<num[j]
                  flag=true;
                  for(int k=l-1;k>i;k--){//从右往左寻找第一个比num[i]大的数
                       if(num[k]>num[i]){//两数交换
                            int temp=num[k];
                            num[k]=num[i];
                            num[i]=temp;
                            break;
                       }
                  }
                  for(int k=j,t=l-1;k<t;k++,t--){//从j开始到数组最后一个元素反转
                       int temp=num[k];
                       num[k]=num[t];
                       num[t]=temp;
                  }
             }
        }
        if(!flag){//如果不存在i<j&&num[i]<num[j],表示该序列为最后一个序列,则从小到大排列
             Arrays.sort(num);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值