Skip to content

Commit 3fb671e

Browse files
committed
feat: add 3Sum
1 parent c8ee8f7 commit 3fb671e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ https://neetcode.io/roadmap
1717
| 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | Medium | [TypeScript](./TypeScript/128.longest-consecutive-sequence.ts) | Arrays & Hashing |
1818
| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | Easy | [TypeScript](./TypeScript/125.valid-palindrome.ts) | Two Pointers |
1919
| 167 | [Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | Medium | [TypeScript](./TypeScript/167.two-sum-ii-input-array-is-sorted.ts) | Two Pointers |
20+
| 15 | [3Sum](https://leetcode.com/problems/3sum/) | Medium | [TypeScript](./TypeScript/15.3sum.ts) | Two Pointers |

TypeScript/15.3sum.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
function threeSum(nums: number[]): number[][] {
2+
const result: number[][] = [];
3+
nums.sort((a, b) => a - b);
4+
5+
for (let i = 0; i < nums.length - 2; i++) {
6+
if (nums[i] > 0) break;
7+
if (nums[i] === nums[i - 1]) continue;
8+
9+
let l = i + 1;
10+
let r = nums.length - 1;
11+
12+
while (l < r) {
13+
const sum = nums[i] + nums[l] + nums[r];
14+
15+
if (sum === 0) {
16+
result.push([nums[i], nums[l], nums[r]]);
17+
r -= 1;
18+
l += 1;
19+
while (nums[l] === nums[l - 1]) l++;
20+
} else if (sum > 0) {
21+
r--;
22+
} else {
23+
l++;
24+
}
25+
}
26+
}
27+
28+
return result;
29+
}

0 commit comments

Comments
 (0)