forked from codesONLY/JavaScriptONLY
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextPermutation.js
More file actions
33 lines (30 loc) · 747 Bytes
/
nextPermutation.js
File metadata and controls
33 lines (30 loc) · 747 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
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
let index_1 = -1;
let index_2 = -1;
for(let i=nums.length-2; i>=0; i--){
if(nums[i] < nums[i+1]){
index_1 = i;
break;
}
}
for(let i=nums.length-1; i>=0; i--){
if(nums[i] > nums[index_1]){
index_2 = i;
break;
}
}
// swap
[nums[index_1], nums[index_2]] = [nums[index_2], nums[index_1]]
// reverse the latter half
let x = index_1 + 1;
let y = nums.length - 1
while (x < y){
[nums[x], nums[y]] = [nums[y], nums[x]]
x++;
y--;
}
};