leetcode题解-31. 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,31,3,2
3,2,11,2,3
1,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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值