Skip to content

Commit e0b014b

Browse files
committed
3sum
1 parent e061a11 commit e0b014b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

3sum/taewanseoul.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 15. 3Sum
3+
* Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
4+
* Notice that the solution set must not contain duplicate triplets.
5+
*
6+
* https://leetcode.com/problems/3sum/description/
7+
*/
8+
function threeSum(nums: number[]): number[][] {
9+
nums.sort((a, b) => a - b);
10+
const triplets: number[][] = [];
11+
12+
for (let i = 0; i < nums.length - 2; i++) {
13+
if (nums[i] > 0 || nums[i] === nums[i - 1]) {
14+
continue;
15+
}
16+
17+
let low = i + 1;
18+
let high = nums.length - 1;
19+
20+
while (low < high) {
21+
const sum = nums[i] + nums[low] + nums[high];
22+
if (sum < 0) {
23+
low++;
24+
} else if (sum > 0) {
25+
high--;
26+
} else {
27+
triplets.push([nums[i], nums[low], nums[high]]);
28+
29+
while (low < high && nums[low] === nums[low + 1]) {
30+
low++;
31+
}
32+
while (low < high && nums[high] === nums[high - 1]) {
33+
high--;
34+
}
35+
low++;
36+
high--;
37+
}
38+
}
39+
}
40+
41+
return triplets;
42+
}
43+
44+
// O(n^2) time
45+
// O(n) space

0 commit comments

Comments
 (0)