-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path31-Next-Permutation.js
More file actions
38 lines (32 loc) · 871 Bytes
/
31-Next-Permutation.js
File metadata and controls
38 lines (32 loc) · 871 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
const nextPermutation = (nums) => {
const swap = (i, j, arr) => {
[arr[i], arr[j]] = [arr[j], arr[i]];
};
const reverseNext = (idx, arr) => {
let start = idx;
let end = arr.length - 1;
while (start < end) {
swap(start, end, arr);
start++;
end--;
}
};
const nextLarge = (idx, arr) => {
for (let i = arr.length - 1; i > idx; i--) {
if (arr[i] > arr[idx]) return i;
}
};
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
const large = nextLarge(i, nums);
swap(i, large, nums);
reverseNext(i + 1, nums);
return;
}
}
nums.reverse();
};