Skip to content

Commit b0e6b74

Browse files
authored
Update 15-3sum.js
1 parent 296904d commit b0e6b74

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

15-3sum.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,37 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
const threeSum = function(nums) {
6+
const res = [], n = nums.length
7+
nums.sort((a, b) => a - b)
8+
9+
for(let i = 0; i < n; i++) {
10+
const target = -nums[i]
11+
let l = i + 1, r = n - 1
12+
while(l < r) {
13+
const sum = nums[l] + nums[r]
14+
if(sum > target) r--
15+
else if(sum < target) l++
16+
else {
17+
const e = [nums[i], nums[l], nums[r]]
18+
res.push(e)
19+
while(l + 1 < r && nums[l + 1] === nums[l]) l++
20+
while(r - 1 > l && nums[r - 1] === nums[r]) r--
21+
l++
22+
r--
23+
}
24+
}
25+
while(i + 1 < n && nums[i] === nums[i + 1]) i++
26+
}
27+
28+
29+
return res
30+
};
31+
32+
// another
33+
34+
135
/**
236
* @param {number[]} nums
337
* @return {number[][]}

0 commit comments

Comments
 (0)