-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path15. 3Sum.js
39 lines (34 loc) · 951 Bytes
/
15. 3Sum.js
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
32
33
34
35
36
37
38
39
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
nums.sort((a, b) => a - b);
let res = [];
for (let i = 0; i < nums.length - 2; i++) {
// skipping the duplicate elements
if (i > 0 && nums[i] == nums[i - 1]) continue;
let j = i + 1;
let k = nums.length - 1;
// Two sum approach
while (j < k) {
let sum = nums[j] + nums[k];
if (sum == -nums[i]) {
res.push([nums[i], nums[j], nums[k]]);
// skipping the duplicate elements
while (nums[j] == nums[j + 1]) j++;
while (nums[k] == nums[k - 1]) k--;
k--;
j++;
}
else if (sum > -nums[i]) {
k--;
}
else {
j++;
}
}
}
return res;
};
console.log(threeSum([-1, 0, 1, 2, -1, -4]));