-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0031-next-permutation.js
More file actions
55 lines (49 loc) · 1.31 KB
/
0031-next-permutation.js
File metadata and controls
55 lines (49 loc) · 1.31 KB
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
48
49
50
51
52
53
54
55
/**
* Next Permutation
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
var nextPermutation = function (nums) {
const localSwap = (arrItems, firstIdx, secondIdx) => {
const temporaryValue = arrItems[firstIdx];
arrItems[firstIdx] = arrItems[secondIdx];
arrItems[secondIdx] = temporaryValue;
};
const localReverse = (arrElements, startPoint) => {
let leftPointer = startPoint;
let rightPointer = arrElements.length - 1;
while (leftPointer < rightPointer) {
localSwap(arrElements, leftPointer, rightPointer);
leftPointer++;
rightPointer--;
}
};
let firstDecreasingIndex = -1;
for (
let loopCounterOne = nums.length - 2;
loopCounterOne >= 0;
loopCounterOne--
) {
if (nums[loopCounterOne] < nums[loopCounterOne + 1]) {
firstDecreasingIndex = loopCounterOne;
break;
}
}
if (firstDecreasingIndex === -1) {
localReverse(nums, 0);
return;
}
let swapCandidateIndex = -1;
for (
let loopCounterTwo = nums.length - 1;
loopCounterTwo > firstDecreasingIndex;
loopCounterTwo--
) {
if (nums[loopCounterTwo] > nums[firstDecreasingIndex]) {
swapCandidateIndex = loopCounterTwo;
break;
}
}
localSwap(nums, firstDecreasingIndex, swapCandidateIndex);
localReverse(nums, firstDecreasingIndex + 1);
};