-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0031-NextPermutation.js
More file actions
54 lines (45 loc) · 1.26 KB
/
0031-NextPermutation.js
File metadata and controls
54 lines (45 loc) · 1.26 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
//-----------------------------------------------------------------------------
// Runtime: 76ms
// Memory Usage: 37.6 MB
// Link: https://leetcode.com/submissions/detail/385822370/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
const swap = function(i, j) {
let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
};
const reverse = function(start) {
let end = nums.length - 1;
while (start < end) {
swap(start, end);
start++;
end--;
}
};
var i = nums.length - 1;
while (i > 0 && nums[i - 1] >= nums[i]) {
i--;
}
if (i <= 0) {
nums.reverse();
return;
}
var j = nums.length - 1;
while (j >= 0 && nums[i - 1] >= nums[j]) {
j--;
}
swap(i - 1, j);
reverse(i);
};
return {
nextPermutation: nextPermutation
};
};
module.exports = solution();