Skip to content

Commit 5d961bf

Browse files
committed
solved: 31
1 parent ff5a166 commit 5d961bf

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

code/31.next-permutation.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// @leet start
2+
/**
3+
* swap the first number that is smaller than the number after it
4+
*/
5+
function nextPermutation(nums: number[]): void {
6+
let i = nums.length - 2;
7+
while (i >= 0 && nums[i] >= nums[i + 1]) {
8+
i--;
9+
}
10+
11+
if (i >= 0) {
12+
let j = nums.length - 1;
13+
while (j >= 0 && nums[j] <= nums[i]) {
14+
j--;
15+
}
16+
17+
[nums[i], nums[j]] = [nums[j], nums[i]];
18+
}
19+
20+
// reverse the rest
21+
22+
const s = nums.slice(i + 1);
23+
s.reverse();
24+
s.forEach((v, index) => {
25+
nums[i + 1 + index] = v;
26+
});
27+
}
28+
// @leet end
29+

0 commit comments

Comments
 (0)