资讯专栏INFORMATION COLUMN

31. Next Permutation

未东兴 / 259人阅读

摘要:边界条件,这时候之后只有一个值数组一直递减,这时候变成,没有,只需要从到的所有数。

31. Next Permutation

题目链接:https://leetcode.com/problems...

这道题就是找规律,可以看出来下一个permutation的规律是:从右往左扫,找到第一个满足:nums[i-1] < nums[i]条件的,再找到从右到左第一个比nums[i-1]大的数,把它们swap,再把所有i-1之后的数字swap即可。边界条件:1. i = nums.length - 1,这时候i-1之后只有一个值, 2. 数组一直递减,这时候i变成0,没有nums[i-1]swap,只需要swap从0到nums.length - 1的所有数。

public class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 1;
        while(i > 0) {
            if(nums[i-1] < nums[i]) break;
            i--;
        }
        // i = 0, decreasing
        if(i != 0) {
            int j = nums.length - 1;
            while(j >= 0) {
                if(nums[j] > nums[i-1]) break;
                j--;
            }
            swap(nums, i-1, j);
        }
        
        // swap all elements after i-1
        int end = nums.length - 1;
        while(i < end) swap(nums, i++, end--);
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66639.html

相关文章

  • leetcode 31 Next Permutation

    摘要:我们所找到的这个元素就是排序需要改变的第一个元素。然后我们选取一个刚好大于此元素的数,与当前元素进行替换。并对后面的所有元素重新按照升序排列就可以得到最终的答案。 题目详情 Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of...

    binaryTree 评论0 收藏0
  • leetcode31 Next Permutation

    摘要:如果当前数字代表的整数值已经是所有排列组合中的最大值,则返回当前数字组成的最小值。可是这意味着大量无用的数字的生成和比较。一个数字中的各个位上的数如何调整顺序才能获得一个最小的更大值。其次,要保证移动之后,高位以后的值为最小值。 题目要求 Implement next permutation, which rearranges numbers into the lexicographi...

    hedzr 评论0 收藏0
  • 31. Next Permutation

    摘要:比如我们很容易知道下一个数字是。从尾到头找,第一段的部分出现。后面的部分就可以有更大的组合。这里是在递减序列中找到下一个比大的数字,作为序列的头。尾部的递减序列变成递增序列。 Implement next permutation, which rearranges numbers into the lexicographically next greater permutation o...

    denson 评论0 收藏0
  • [LintCode] Next Permutation II [Next Permutation]

    摘要:从末位向前遍历,假设循环开始全是倒序排列,如当第一次出现正序的时候,如的和此时从数列末尾向前循环到,找到第一个比大的交换这两个数,变成倒置第位到末位的数为正序排列这里的是完全倒置的排列,如,即上面循环的情况完全没有出现, Problem Implement next permutation, which rearranges numbers into the lexicographic...

    mikasa 评论0 收藏0
  • [Leetcode] Next Permutation 下一个排列

    摘要:因为增加高位会带来更大的增益。所以对于一个长为的序列,我们增加第位的前提是,前位已经达到了最大排列方法。因为是找下一个数,所以我们要找一个比小却尽可能大的数,所以找到。把换到的位置后,后三位仍然是个降序的排列。 Next Permutation Implement next permutation, which rearranges numbers into the lexicogr...

    young.li 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<