31 Next Permutation

1. Question

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

2. Implementation

class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 1;
        while (i > 0 && nums[i - 1] >= nums[i]) {
            --i;
        }

        if (i > 0) {
            int j = nums.length - 1;

            while (j >= i && nums[i - 1] >= nums[j]) {
                --j;
            }

            swap(nums, i - 1, j);
        }
        reverse(nums, i, nums.length - 1);
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            swap(nums, start , end);
            ++start;
            --end;
        }
    }
}

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)

Last updated