美文网首页
Next Permutation(Medium)

Next Permutation(Medium)

作者: 海生2018 | 来源:发表于2019-11-05 20:15 被阅读0次

    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,31,3,2
    3,2,11,2,3
    1,1,51,5,1


    Solution:

    class Solution {
        public void nextPermutation(int[] nums) {
            if(nums==null) return;
            int i=nums.length-2;
            while(i>=0&&nums[i+1]<=nums[i]){
                i--;
            }
            if(i>=0){
                int j=nums.length-1;
                while(j>i&&nums[j]<=nums[i]){
                    j--;
                }
                swap(i,j,nums);
            }
            reverse(i+1,nums);
        }
    
        private void reverse(int i,int[] a){
            int l=i,r=a.length-1;
                while(l<r){
                    swap(l,r,a);
                    l++;r--;
                }
        }
        private void swap(int i,int j,int[] a){
            int tmp=a[j];
            a[j]=a[i];
            a[i]=tmp;
        }
    }
    

    时间O(n)
    空间O(1)

    更像是规律题,不过我题都没读懂,大意是找下一个排列,如果数组降序则说明是最后一种排列,下一种就是最初的状态(升序)。言外之意是每个排列,从右边遍历到左边,数字应该是依次升序,找到不是升的那个数字,和右边第一个高于它的数字交换,然后反转它的位置(注意这个它,是不是升的那个数字xD)后一个开始的数组。

    相关文章

      网友评论

          本文标题:Next Permutation(Medium)

          本文链接:https://www.haomeiwen.com/subject/dfiebctx.html