【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 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

 

 

Solution:

We can provide several examples to find out how to get next permutation.

123413 -> 123431

1234852 -> 1235248

We can find out that there are consecutive numbers with descending order around tail, say 852, so there is a point with maximum number, it would be 8 in this case. In order to find the next permutation, we need to find a number (for example k)in the descending order consectutive numbers which is just greater than the number(for example j) right before maximum point, 4 in this case, and swap k with j.  After swap them, the number starting from maximum point is still in descending order (think about it). Then arrange the new descending order numbers starting from maximum point to accending order.

Time complexity: O(n)

 

Code: beat 90.99%

public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int indexMax = nums.length - 1;
        while (indexMax > 0 && nums[indexMax] <= nums[indexMax - 1]) {
            indexMax--;
        }
        
        if (indexMax == 0) {
            reverse(nums, 0);
            return;
        }
        int j = nums.length - 1;
        while (j >= indexMax && nums[j] <= nums[indexMax - 1]){
            j--;
        }
        swap(nums, j, indexMax - 1);
        reverse(nums, indexMax);
        return;
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;   
    }
    private void reverse(int[] nums, int start) {
        int i = start, j = nums.length - 1;
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值