forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyer0705.ts
More file actions
31 lines (25 loc) · 691 Bytes
/
hyer0705.ts
File metadata and controls
31 lines (25 loc) · 691 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function threeSum(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const result: number[][] = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
const target = -nums[i];
let j = i + 1;
let k = nums.length - 1;
while (j < k) {
const currentSum = nums[j] + nums[k];
if (target < currentSum) {
k--;
} else if (target > currentSum) {
j++;
} else {
result.push([nums[i], nums[j], nums[k]]);
j++;
k--;
while (j < k && nums[j] === nums[j - 1]) j++;
while (j < k && nums[k] === nums[k + 1]) k--;
}
}
}
return result;
}