# LeetCode Solution, Medium, 31. Next Permutation

# [31. Next Permutation](https://leetcode.com/problems/next-permutation/)

## 題目敘述

A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order.

- For example, for `arr = [1,2,3]`, the following are considered permutations of `arr`: `[1,2,3]`, `[1,3,2]`, `[3,1,2]`, `[2,3,1]`.

The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

- For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`.
- Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`.
- While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement.

Given an array of integers `nums`, _find the next permutation of_ `nums`.

The replacement must be [in place](http://en.wikipedia.org/wiki/In-place_algorithm) and use only constant extra memory.

**Example 1:**

    Input: nums = [1,2,3]
    Output: [1,3,2]

**Example 2:**

    Input: nums = [3,2,1]
    Output: [1,2,3]

**Example 3:**

    Input: nums = [1,1,5]
    Output: [1,5,1]

**Constraints:**

- `1 <= nums.length <= 100`
- `0 <= nums[i] <= 100`

### 題目翻譯

給一個整數陣列 `nums`，需要找出此排序之後的下一個大的排序。如果已經是最大的排序的話就升序輸出。

## 解法解析

1. 從結尾往開頭尋找，找到第一個降冪的值 `x`
2. 從第一步找到的值 `x` 的位置到結尾的這段資料中，找到大於 `x` 中的最小值 `y` (例如 `x = 4`, `x-> n-1` 中有 5, 6, 9，則選擇 5)
3. 將 `x` 和 `y` 的位置互換
4. 將 `x-> n-1` 的值做從小到大排序

### 解法範例

#### Go

```go
func nextPermutation(nums []int) {
	nlen := len(nums)
	if nlen <= 1 {
		return
	}

	for i := nlen - 1; i > 0; i-- {
		if nums[i] <= nums[i-1] {
			continue
		}

		j := i
		for ; j < nlen-1; j++ {
			if nums[j] > nums[i-1] && nums[j+1] <= nums[i-1] {
				break
			}
		}

		nums[i-1], nums[j] = nums[j], nums[i-1]
		reverse(nums[i:])
		return
	}

	// in case an arrangement is impossible
	reverse(nums)
}

func reverse(nums []int) {
	for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
		nums[i], nums[j] = nums[j], nums[i]
	}
}
```

#### JavaScript

```javascript
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function (nums) {
    function swap(i, j) {
        const temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    function reverse(start) {
        let end = nums.length - 1;
        while (start < end) {
            swap(start, end);
            start++;
            end--;
        }
    }

    let i = nums.length - 2;
    while (i >= 0 && nums[i + 1] <= nums[i]) {
        i--;
    }

    if (i >= 0) {
        let j = nums.length - 1;
        while (j >= 0 && nums[j] <= nums[i]) {
            j--;
        }
        swap(i, j);
    }
    reverse(i + 1);
};
```

#### Kotlin

```kotlin
class Solution {
    fun nextPermutation(nums: IntArray) {
        var i = nums.size - 2

        while (i >= 0 && nums[i + 1] <= nums[i]) {
            i--
        }

        if (i >= 0) {
            var j = nums.size - 1
            while (j >= 0 && nums[j] <= nums[i]) {
                j--
            }
            swap(nums, i, j)
        }
        reverse(nums, i + 1)
    }

    fun swap(nums: IntArray, i: Int, j: Int) {
        val temp = nums[i]
        nums[i] = nums[j]
        nums[j] = temp
    }

    fun reverse(nums: IntArray, i: Int) {
        var left = i
        var right = nums.size - 1
        while (left < right) {
            swap(nums, left, right)
            left++
            right--
        }
    }
}
```

#### PHP

```php
class Solution
{

    /**
     * @param Integer[] $nums
     * @return NULL
     */
    function nextPermutation(&$nums)
    {
        $length = count($nums);
        $i = $length - 2;
        while ($i >= 0 && $nums[$i] >= $nums[$i + 1]) {
            $i--;
        }
        if ($i >= 0) {
            $j = $length - 1;
            while ($nums[$i] >= $nums[$j]) {
                $j--;
            }
            [$nums[$i], $nums[$j]] = [$nums[$j], $nums[$i]];
        }

        $revStart = $i + 1;
        $revEnd = $length - 1;
        while ($revStart < $revEnd) {
            [$nums[$revStart], $nums[$revEnd]] = [$nums[$revEnd], $nums[$revStart]];
            $revStart++;
            $revEnd--;
        }
    }
}
```

#### Python

```python
class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i = len(nums) - 2
        while i >= 0 and nums[i] >= nums[i + 1]:
            i -= 1
        if i >= 0:
            j = len(nums) - 1
            while nums[i] >= nums[j]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]

        rev_start = i + 1
        rev_end = len(nums) - 1
        while rev_start < rev_end:
            nums[rev_start], nums[rev_end] = nums[rev_end], nums[rev_start]
            rev_start += 1
            rev_end -= 1
```

#### Rust

```rust
```

#### Swift

```swift
class Solution {
  func reverse(_ nums: inout [Int], _ left: Int, _ right: Int) {
    var left = left
    var right = right

    while left < right {
      nums.swapAt(left, right)
      left += 1
      right -= 1
    }
  }

  func nextPermutation(_ nums: inout [Int]) {
    guard nums.count > 1 else {
      return
    }

    var idx1 = nums.count - 2
    while idx1 >= 0 && nums[idx1] >= nums[idx1 + 1] {
      idx1 -= 1
    }

    if idx1 >= 0 {
      var idx2 = nums.count - 1
      while idx2 >= 0 && nums[idx2] <= nums[idx1] {
        idx2 -= 1
      }
      nums.swapAt(idx1, idx2)
    }
    reverse(&nums, idx1 + 1, nums.count - 1)
  }
}
```

