Next Permutation

Array

Medium

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

Analysis

找规律题。

例子🌰 :

[1,2,5,4,3,0]
  • 从右往左,找到第一个小于右边的数,也就是第一个不满足递增规律的数字,下标i

    • 例子中是 2

  • 在 (i, nums.length)范围内,寻找恰好比nums[i]大的数,下标j

    • 例子中是 3

  • 交换i, j元素

    • 例子中:交换2,3的位置

  • 逆序[i + 1, nums.length)的子数组(subarray)

    • 例子结果结果:[1,3,0,2,4,5]

这个规律现场很难想出来,就当一个基本事实规律记住好了...不然这题应该是Hard难度。

Solution

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

    private void reverse(int[] nums, int start) {
        int end = nums.length - 1;
        while (start < end) {
            swap(nums, start, end);
            start++;
            end--;
        }
    }
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

https://leetcode.com/problems/next-permutation/solution/

Last updated