Skip to content

Commit ad651ab

Browse files
committed
Update next permutation
1 parent 2e7fec4 commit ad651ab

File tree

1 file changed

+17
-38
lines changed

1 file changed

+17
-38
lines changed

src/array/next-permutation.js

+17-38
Original file line numberDiff line numberDiff line change
@@ -18,51 +18,30 @@
1818
* @return {void} Do not return anything, modify nums in-place instead.
1919
*/
2020
const nextPermutation = nums => {
21-
if (nums == null || nums.length == 0) {
22-
return;
23-
}
24-
2521
const n = nums.length;
2622

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+
}
4735
}
48-
p++;
4936
}
5037

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();
5639
};
5740

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]]);
6342

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--);
6746
}
6847
};

0 commit comments

Comments
 (0)