Skip to content

Commit 06c0af1

Browse files
committed
update: 31
1 parent bef9603 commit 06c0af1

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
3131
| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [JavaScript](./src/remove-element/res.js) | Easy |
3232
| 28 | [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [JavaScript](./src/implement-strstr/res.js) | Easy |
3333
| 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [JavaScript](./src/divide-two-integers/res.js) | Medium |
34+
| 31 | [next-permutation](https://leetcode.com/problems/next-permutation/) | [TypeScript](./src/next-permutation/res.ts) | Medium |
3435
| 33 | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [JavaScript](./src/search-in-rotated-sorted-array/res.js) | Medium |
3536
| 34 | [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [JavaScript](./src/search-for-a-range/res.js) | Medium |
3637
| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [JavaScript](./src/search-insert-position/res.js) | Easy |

src/next-permutation/res.ts

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
Do not return anything, modify nums in-place instead.
3+
*/
4+
function nextPermutation(nums: number[]): void {
5+
let currentPointer = nums.length - 1;
6+
let mutationCount = 0;
7+
8+
if (currentPointer < 1) {
9+
return ;
10+
}
11+
12+
while (!mutationCount || currentPointer <= nums.length-1 && currentPointer > 0) {
13+
mutationCount++;
14+
if (currentPointer > 0 && nums[currentPointer] > nums[currentPointer-1]) {
15+
currentPointer--;
16+
break;
17+
}
18+
19+
currentPointer--;
20+
}
21+
22+
let swapPointer = nums.length-1;
23+
while(swapPointer > 0 && nums[swapPointer] <= nums[currentPointer]) {
24+
swapPointer--;
25+
}
26+
27+
if (!currentPointer && !swapPointer) {
28+
nums.sort((a, b) => a - b);
29+
} else if (currentPointer === nums.length-2) {
30+
const swapPointer = currentPointer+1;
31+
const swapValue = nums[swapPointer];
32+
nums[swapPointer] = nums[currentPointer];
33+
nums[currentPointer] = swapValue;
34+
} else {
35+
// swap
36+
const swapValue = nums[swapPointer];
37+
nums[swapPointer] = nums[currentPointer];
38+
nums[currentPointer] = swapValue;
39+
40+
const restList = nums.slice(currentPointer + 1);
41+
restList.sort((a, b) => a - b);
42+
43+
for (let j = currentPointer + 1; j < nums.length; j++) {
44+
nums[j] = restList[j-currentPointer-1];
45+
}
46+
}
47+
};

0 commit comments

Comments
 (0)