Skip to content

Commit 9450188

Browse files
committed
solve: Week 02 3 sum
1 parent 5badd68 commit 9450188

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

3sum/eunice-hong.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
function threeSum(nums: number[]): number[][] {
2+
// Sort the array to make it easier to find triplets that sum to zero
3+
nums.sort((a, b) => a - b);
4+
const result: number[][] = [];
5+
6+
// Iterate through the array to find triplets that sum to zero
7+
for (let i = 0; i < nums.length - 2; i++) {
8+
// Skip duplicates
9+
if (i > 0 && nums[i] === nums[i - 1]) continue;
10+
11+
// Use two pointers to find the other two numbers
12+
let left = i + 1;
13+
let right = nums.length - 1;
14+
15+
while (left < right) {
16+
const sum = nums[i] + nums[left] + nums[right];
17+
if (sum === 0) {
18+
// Add the triplet to the result array
19+
result.push([nums[i], nums[left], nums[right]]);
20+
left++;
21+
right--;
22+
// Skip duplicates
23+
while (left < right && nums[left] === nums[left - 1]) left++;
24+
while (left < right && nums[right] === nums[right + 1]) right--;
25+
} else if (sum < 0) {
26+
// Move the left pointer to the right to increase the sum
27+
left++;
28+
} else {
29+
// Move the right pointer to the left to decrease the sum
30+
right--;
31+
}
32+
}
33+
}
34+
35+
return result;
36+
}

0 commit comments

Comments
 (0)