-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.3-sum.js
38 lines (35 loc) · 824 Bytes
/
15.3-sum.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
/*
* @lc app=leetcode id=15 lang=javascript
*
* [15] 3Sum
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
const result = [];
if (nums.length < 3) return result;
nums.sort((a, b) => a - b);
const target = 0;
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
if (nums[i] > target) break;
let j = i + 1;
let k = nums.length - 1;
while (j < k) {
const sum = nums[i] + nums[j] + nums[k];
if (sum === target) {
result.push([nums[i], nums[j], nums[k]]);
while (nums[j] === nums[j + 1]) j++;
while (nums[k] === nums[k - 1]) k--;
j++;
k--;
} else if (sum < target) j++;
else k--;
}
}
return result;
};
// @lc code=end