|
18 | 18 | * @return {void} Do not return anything, modify nums in-place instead.
|
19 | 19 | */
|
20 | 20 | const nextPermutation = nums => {
|
21 |
| - if (nums == null || nums.length == 0) { |
22 |
| - return; |
23 |
| - } |
24 |
| - |
25 | 21 | const n = nums.length;
|
26 | 22 |
|
27 |
| - // step 1. scan from right and find the digit that is lower than the one on its right |
28 |
| - let p = n - 1; |
29 |
| - while (p > 0 && nums[p - 1] >= nums[p]) { |
30 |
| - p--; |
31 |
| - } |
32 |
| - |
33 |
| - if (p == 0) { |
34 |
| - // no such digit is found, the whole array is sorted in descending order |
35 |
| - // we can simply reverse it |
36 |
| - reverse(nums, 0, n - 1); |
37 |
| - return; |
38 |
| - } |
39 |
| - |
40 |
| - // step 2. from p, find the digit that is just larger than nums[p - 1] |
41 |
| - let i = p - 1; |
42 |
| - let j = p; |
43 |
| - |
44 |
| - while (p < n) { |
45 |
| - if (nums[p] > nums[i] && nums[p] <= nums[j]) { |
46 |
| - j = p; |
| 23 | + // Step 1. scan from right and find the first digit that is less than its right |
| 24 | + for (let i = n - 2; i >= 0; i--) { |
| 25 | + if (nums[i] < nums[i + 1]) { |
| 26 | + // Step 2. scan from right and find the digit that is larger than nums[i] |
| 27 | + for (let j = n - 1; j > i; j--) { |
| 28 | + if (nums[j] > nums[i]) { |
| 29 | + // Step 3. swap nums[i] and nums[j], reverse from i+1 |
| 30 | + swap(nums, i, j); |
| 31 | + reverse(nums, i + 1, n - 1); |
| 32 | + return; |
| 33 | + } |
| 34 | + } |
47 | 35 | }
|
48 |
| - p++; |
49 | 36 | }
|
50 | 37 |
|
51 |
| - // step 3. swap i & j |
52 |
| - swap(nums, i, j); |
53 |
| - |
54 |
| - // step 4. reverse the digits after i |
55 |
| - reverse(nums, i + 1, n - 1); |
| 38 | + nums.reverse(); |
56 | 39 | };
|
57 | 40 |
|
58 |
| -const swap = (nums, i, j) => { |
59 |
| - const t = nums[i]; |
60 |
| - nums[i] = nums[j]; |
61 |
| - nums[j] = t; |
62 |
| -}; |
| 41 | +const swap = (nums, i, j) => ([nums[i], nums[j]] = [nums[j], nums[i]]); |
63 | 42 |
|
64 |
| -const reverse = (nums, i, j) => { |
65 |
| - while (i < j) { |
66 |
| - swap(nums, i++, j--); |
| 43 | +const reverse = (nums, start, end) => { |
| 44 | + while (start < end) { |
| 45 | + swap(nums, start++, end--); |
67 | 46 | }
|
68 | 47 | };
|
0 commit comments