Skip to content

Commit ba73927

Browse files
committed
3Sum
1 parent b83f655 commit ba73927

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

3sum/casentino.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function threeSum(nums: number[]): number[][] {
2+
const sortedNums = nums.sort((a, b) => a - b);
3+
const results: number[][] = [];
4+
for (let i = 0; i < sortedNums.length - 2; i++) {
5+
const current = sortedNums[i];
6+
if (current > 0) {
7+
return results;
8+
}
9+
if (i > 0 && current === sortedNums[i - 1]) {
10+
continue;
11+
}
12+
let left = i + 1;
13+
let right = sortedNums.length - 1;
14+
while (left < right) {
15+
const sum = current + sortedNums[left] + sortedNums[right];
16+
if (sum > 0) {
17+
right -= 1;
18+
} else if (sum < 0) {
19+
left += 1;
20+
} else {
21+
results.push([current, sortedNums[left], sortedNums[right]]);
22+
left += 1;
23+
right -= 1;
24+
while (left < right && sortedNums[left] === sortedNums[left - 1]) {
25+
left += 1;
26+
}
27+
while (left < right && sortedNums[right] === sortedNums[right + 1]) {
28+
right -= 1;
29+
}
30+
}
31+
}
32+
}
33+
return results;
34+
}

0 commit comments

Comments
 (0)