-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
47 lines (40 loc) · 1.34 KB
/
res.ts
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
39
40
41
42
43
44
45
46
47
/**
Do not return anything, modify nums in-place instead.
*/
function nextPermutation(nums: number[]): void {
let currentPointer = nums.length - 1;
let mutationCount = 0;
if (currentPointer < 1) {
return ;
}
while (!mutationCount || currentPointer <= nums.length-1 && currentPointer > 0) {
mutationCount++;
if (currentPointer > 0 && nums[currentPointer] > nums[currentPointer-1]) {
currentPointer--;
break;
}
currentPointer--;
}
let swapPointer = nums.length-1;
while(swapPointer > 0 && nums[swapPointer] <= nums[currentPointer]) {
swapPointer--;
}
if (!currentPointer && !swapPointer) {
nums.sort((a, b) => a - b);
} else if (currentPointer === nums.length-2) {
const swapPointer = currentPointer+1;
const swapValue = nums[swapPointer];
nums[swapPointer] = nums[currentPointer];
nums[currentPointer] = swapValue;
} else {
// swap
const swapValue = nums[swapPointer];
nums[swapPointer] = nums[currentPointer];
nums[currentPointer] = swapValue;
const restList = nums.slice(currentPointer + 1);
restList.sort((a, b) => a - b);
for (let j = currentPointer + 1; j < nums.length; j++) {
nums[j] = restList[j-currentPointer-1];
}
}
};