-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.js
More file actions
53 lines (42 loc) · 1.56 KB
/
3Sum.js
File metadata and controls
53 lines (42 loc) · 1.56 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* @param {number[]} nums
* @return {number[][]}
*/
// https://leetcode.com/problems/3sum/discuss/281302/JavaScript-with-lots-of-explanatory-comments!
var threeSum = function (nums) {
const results = [];
if (nums.length < 3)
return results;
nums = nums.sort((a, b) => a - b);
for (let i = 0; i < nums.length - 2; i++) {
var firstNum = nums[i];
if (firstNum > 0)
break;
// Remove duplicates
if(i > 0 && firstNum == nums[i - 1])
continue;
let secondNumIndex = i + 1;
let thirdNumIndex = nums.length - 1;
while(secondNumIndex < thirdNumIndex) {
let tempSum = firstNum + nums[secondNumIndex] + nums[thirdNumIndex];
if (tempSum == 0){
results.push([firstNum, nums[secondNumIndex], nums[thirdNumIndex]]);
// Remove duplicates
while (nums[secondNumIndex] == nums[secondNumIndex + 1])
secondNumIndex++
while (nums[thirdNumIndex] == nums[thirdNumIndex - 1])
thirdNumIndex--
secondNumIndex++;
thirdNumIndex--;
}
else if(tempSum < 0)
secondNumIndex++; //increment so the result will be larger
else
thirdNumIndex--; //decrement so the result will be smaller
}
}
return results;
};
var nums = [0, 0, 0];
console.log(threeSum(nums))
console.log(undefined)