Skip to content

Commit 39169ca

Browse files
committed
Time: 14 ms (54.9%), Space: 57.4 MB (33%) - LeetHub
source:d586f9a3c6b765e2f3ceb39ffc91263bdac61c99
1 parent 12423af commit 39169ca

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var threeSumClosest = function(nums, target) {
7+
nums.sort((a, b) => a - b);
8+
let threeSum = nums[0] + nums[1] + nums[2];
9+
for (let i = 0; i < nums.length - 2; i++) {
10+
let left = i + 1;
11+
let right = nums.length - 1;
12+
13+
while (left < right) {
14+
const sum = nums[i] + nums[left] + nums[right];
15+
if (sum === target) return sum;
16+
if (Math.abs(target - sum) < Math.abs(target - threeSum)) {
17+
threeSum = sum;
18+
}
19+
20+
if (sum < target) {
21+
left++;
22+
} else {
23+
right--;
24+
}
25+
}
26+
}
27+
28+
return threeSum;
29+
};

0 commit comments

Comments
 (0)