Skip to content

Commit

Permalink
practice leetcode 31
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanGolphi committed Jan 7, 2025
1 parent 4ca9bb7 commit 13b2513
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ This is the repository records my Algorithms & Data structures learning with
| 25 | [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) | [Js](./sourceFile/Js/25_ReverseNodesInKGroup.js) | hard | LinkedList |
| 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [Js](./sourceFile/Js/26_RemoveDuplicatesFromSortedArray.js) [Ts](./sourceFile/typescript/26_RemoveDuplicatesFromSortedArray.ts) | easy | Array |
| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Js](./sourceFile/Js/27_RemoveElements.js) [Ts](./sourceFile/typescript/27_RemoveElement.ts) | easy | Double Pointers |
| 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/) | [Ts](./sourceFile/typescript/31_NextPermutation.ts) | medium | Array |
| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Js](./sourceFile/Js/35_SearchInsertPosition.js) | easy | Binary Search |
| 46 | [Permutations](https://leetcode.com/problems/permutations/) | [Ts](./sourceFile/typescript/46_Permutations.ts) | medium | Backtracking |
| 77 | [Combinations](https://leetcode.com/problems/combinations/) | [Ts](./sourceFile/typescript/77_Combinations.ts) | medium | Backtracking |
Expand Down
45 changes: 45 additions & 0 deletions sourceFile/typescript/31_NextPermutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// @algorithm @lc id=31 lang=typescript
// @title next-permutation
// @test([1,2,3])=[1,3,2]
// @test([3,2,1])=[1,2,3]
// @test([1,1,5])=[1,5,1]
/**
Do not return anything, modify nums in-place instead.
*/
function nextPermutation(nums: number[]): void {
if (nums.length === 1) return;
if (nums.length === 2) {
nums.reverse();
return;
}

let i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}

if (i >= 0) {
let j = nums.length - 1;
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}

let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}

for (
let left = i + 1, right = nums.length - 1;
left < right;
left++, right--
) {
let temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}

const nums = [1, 5, 1];
nextPermutation(nums);
console.log(nums);

0 comments on commit 13b2513

Please sign in to comment.