|
| 1 | +# 31. Next Permutation |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array. |
| 5 | +- Similar Questions: Permutations, Permutations II, Permutation Sequence, Palindrome Permutation II. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers. |
| 10 | + |
| 11 | +If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). |
| 12 | + |
| 13 | +The replacement must be **in-place** and use only constant extra memory. |
| 14 | + |
| 15 | +Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. |
| 16 | + |
| 17 | +```1,2,3``` → ```1,3,2``` |
| 18 | + |
| 19 | +```3,2,1``` → ```1,2,3``` |
| 20 | + |
| 21 | +```1,1,5``` → ```1,5,1``` |
| 22 | + |
| 23 | +## Solution |
| 24 | + |
| 25 | +```javascript |
| 26 | +/** |
| 27 | + * @param {number[]} nums |
| 28 | + * @return {void} Do not return anything, modify nums in-place instead. |
| 29 | + */ |
| 30 | +var nextPermutation = function(nums) { |
| 31 | + var len = nums.length; |
| 32 | + var i = len - 2; |
| 33 | + var j = len - 1; |
| 34 | + |
| 35 | + while (i >= 0 && nums[i] >= nums[i + 1]) i--; |
| 36 | + |
| 37 | + if (i >= 0) { |
| 38 | + while (j > i && nums[j] <= nums[i]) j--; |
| 39 | + swap(nums, i, j); |
| 40 | + reverse(nums, i + 1, len - 1); |
| 41 | + } else { |
| 42 | + reverse(nums, 0, len - 1); |
| 43 | + } |
| 44 | +}; |
| 45 | + |
| 46 | +var swap = function (arr, from, to) { |
| 47 | + var tmp = arr[from]; |
| 48 | + arr[from] = arr[to]; |
| 49 | + arr[to] = tmp; |
| 50 | +}; |
| 51 | + |
| 52 | +var reverse = function (arr, start, end) { |
| 53 | + while (start < end) { |
| 54 | + swap(arr, start, end); |
| 55 | + start++; |
| 56 | + end--; |
| 57 | + } |
| 58 | +}; |
| 59 | +``` |
| 60 | + |
| 61 | +**Explain:** |
| 62 | + |
| 63 | +1. 从后往前找,直到 `nums[i] < nums[i + 1]` |
| 64 | +2. 找到 `i` 后,从后往前找,直到 `nums[j] > nums[i]`,交换 `nums[i]`、`nums[j]`,然后把 `i` 后的倒置一下 |
| 65 | +3. 没找到 `i` 的话,直接倒置一下 |
| 66 | + |
| 67 | +**Complexity:** |
| 68 | + |
| 69 | +* Time complexity : O(n). |
| 70 | +* Space complexity : O(1). |
0 commit comments