# 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**](http://en.wikipedia.org/wiki/In-place_algorithm) 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`

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

```java
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/>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/array/next-permutation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
