[LeetCode]31. Next Permutation

栏目: 编程工具 · 发布时间: 6年前

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

感觉属于那种数学找规律,然后把这个规律用程序表达,写的程序比较简单

找到i满足nums[i]<nums[i+1];

从{i-nums.length-1}中找到比nums[i]大且最小的,其余的按顺序排列

public void nextPermutation(int[] nums) {
    if(nums.length<=1) return;
    int i=nums.length-2;
    for(;i>=0;i--){
        if(nums[i]<nums[i+1]) break;
        if(i==0){
            Arrays.sort(nums);
            return;
        }
    }
    int first=nums[i];
    int[] ends=Arrays.copyOfRange(nums,i,nums.length);
    Arrays.sort(ends);
    int j=0;
    for(;j<ends.length;j++){
        if(ends[j]>first) break;
    }
    nums[i]=ends[j];
    i++;
    for(int k=0;k<ends.length;k++){
        if(j!=k){
            nums[i]=ends[k];
            i++;
        }
    }
}

以上所述就是小编给大家介绍的《[LeetCode]31. Next Permutation》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

OKR工作法

OKR工作法

克里斯蒂娜•沃特克 (Christina Wodtke) / 明道团队 / 中信出版社 / 2017-9-1 / CNY 42.00

《OKR工作法》讲述了一种风靡硅谷科技企业的全新工作模式。 如何激励不同的团队一起工作,全力以赴去实现一个有挑战性的目标? 硅谷的两个年轻人汉娜和杰克,像很多人一样,在萌生了一个创意后,就走上创业之路。但是,很快他们发现好的想法远远不够,必须还有一套适合的管理方法确保梦想能实现。为了让创业团队生存下来,汉娜和杰克遭受了内心的苦苦挣扎和煎熬。他们患上“新奇事物综合症”,什么都想做,导致无......一起来看看 《OKR工作法》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试