-
Notifications
You must be signed in to change notification settings - Fork 3
/
leetcode-31-next-permutation.js
55 lines (38 loc) · 1.16 KB
/
leetcode-31-next-permutation.js
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
/*
# Federico Carrizo
# https://github.com/justfede
31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
Solution Big-O:
O(n)
*/
let input = [1,2,3];
const solution = (nums) => {
let j = nums.length - 1;
let i = j - 1;
while (nums[i + 1] <= nums[i]){
i--;
}
if (~i) {
while (nums[j] <= nums[i]){
j--;
}
swap(nums, i, j);
}
for (let k = i + 1, stop = (i + nums.length) / 2; k < stop; k++)
swap(nums, k, nums.length - k + i);
}
const swap = (nums, i, j) => {
let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
solution(input);
console.log(input);