leetcode题解-31. Next Permutation

来源:互联网 发布:淘宝里的一元秒杀在哪 编辑:程序博客网 时间:2024/05/16 16:19

题目:

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

看到这个题读了很多遍都读不懂,然后就去看答案了==大概的题意就是假设数组是降序排列,然后现在有一个地方出现了反转,例如这样:[5,3,1,9,7,4,2] 在1和9的位置出现异常,我们需要做的就是找到该位置,然后将之后的数组变成升序排列。可以分为下面三个步骤:

  1. 找到反转点
  2. 从尾部向前找到后半区比该值(1)大的数,交换两个数
  3. 将后面的数组排序成升序
    代码入下:
public void nextPermutation(int[] nums) {        /* 1. Reverse find first number which breaks descending order. */        int i=nums.length-1;        for(; i>=1; i--)            if(nums[i-1]<nums[i]) break;        /* if no break found in step 1 */        if(i==0){            /* for case "1" and "1111" */            if(nums.length==1 || nums[0]==nums[1]) return;             /* for case "54321" */            int lo=i, hi=nums.length-1;            while(lo<hi) swap(nums, lo++, hi--);            return;        }        /* 2. Exchange this number with the least number that's greater than this number. */        /* 2.1 Find the least number that's greater using binary search, O(log(nums.length-i)) */        int j = binarySearchLeastGreater(nums, i, nums.length-1, nums[i-1]);        /* 2.2 Exchange the numbers */        if(j!=-1) swap(nums, i-1, j);        /* 3. Reverse sort the numbers after the exchanged number. */        int lo=i, hi=nums.length-1;        while(lo<hi) swap(nums, lo++, hi--);    }    public int binarySearchLeastGreater(int[] nums, int lo, int hi, int key){        while(lo<=hi){            int mid = lo + (hi-lo)/2;            if(nums[mid]>key){                lo = mid+1;            } else {                hi = mid-1;            }        }        return hi;    }    public void swap(int[] nums, int i, int j){        int tmp = nums[j];        nums[j] = nums[i];        nums[i] = tmp;    }
0 0