Skip to content

Commit b0a44ba

Browse files
committed
Update: 0015-3sum.js
1 parent 778fc8c commit b0a44ba

File tree

1 file changed

+28
-46
lines changed

1 file changed

+28
-46
lines changed

javascript/0015-3sum.js

+28-46
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,34 @@
11
/**
2-
* https://leetcode.com/problems/3sum/
3-
* Time O(N ^ 2) | Space O(N)
42
* @param {number[]} nums
53
* @return {number[][]}
64
*/
7-
var threeSum = function (nums, sums = []) {
8-
nums.sort((a, b) => a - b);
9-
10-
for (let first = 0; first < nums.length - 2; first++) {
11-
if (isPrevDuplicate(nums, first)) continue;
12-
13-
const [target, left, right] = [
14-
-nums[first],
15-
first + 1,
16-
nums.length - 1,
17-
];
18-
19-
search(nums, target, left, right, sums);
20-
}
21-
22-
return sums;
23-
};
24-
25-
const isPrevDuplicate = (nums, index) => nums[index - 1] === nums[index];
26-
27-
const isNextDuplicate = (nums, index) => nums[index] === nums[index + 1];
28-
29-
const search = (nums, target, left, right, sums) => {
30-
while (left < right) {
31-
const [leftVal, rightVal] = [nums[left], nums[right]];
32-
const sum = leftVal + rightVal;
33-
34-
const isTarget = sum === target;
35-
if (isTarget) {
36-
sums.push([-target, leftVal, rightVal]);
37-
left++;
38-
right--;
39-
40-
while (left < right && isPrevDuplicate(nums, left)) left++;
41-
while (left < right && isNextDuplicate(nums, right)) right--;
42-
43-
continue;
5+
var threeSum = function(nums) {
6+
const res = [];
7+
nums.sort((a,b) => a-b)
8+
9+
for (let i = 0; i < nums.length; i++) {
10+
const a = nums[i];
11+
if (a > 0) break;
12+
if (i > 0 && a === nums[i - 1]) continue;
13+
14+
let l = i + 1;
15+
let r = nums.length - 1;
16+
while (l < r) {
17+
const threeSum = a + nums[l] + nums[r];
18+
if (threeSum > 0) {
19+
r--;
20+
} else if (threeSum < 0) {
21+
l++;
22+
} else {
23+
res.push([a, nums[l], nums[r]]);
24+
l++;
25+
r--;
26+
while (nums[l] === nums[l - 1] && l < r) {
27+
l++;
28+
}
29+
}
4430
}
45-
46-
const isTargetGreater = sum < target;
47-
if (isTargetGreater) left++;
48-
49-
const isTargetLess = target < sum;
50-
if (isTargetLess) right--;
5131
}
52-
};
32+
return res;
33+
}
34+

0 commit comments

Comments
 (0)