-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path16-3Sum-Closest.js
More file actions
35 lines (27 loc) · 828 Bytes
/
16-3Sum-Closest.js
File metadata and controls
35 lines (27 loc) · 828 Bytes
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
// 16. 3Sum Closest [Medium]
// https://leetcode.com/problems/3sum-closest/
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
const threeSumClosest = (nums, target) => {
nums.sort((a, b) => a - b);
let left;
let right;
let currentSum;
let closestSum = Infinity;
for (let i = 0; i < nums.length - 2; i++) {
left = i + 1;
right = nums.length - 1;
while (left < right) {
currentSum = nums[left] + nums[i] + nums[right];
const currentDiff = Math.abs(target - currentSum);
const closestDiff = Math.abs(target - closestSum);
if (currentDiff < closestDiff) closestSum = currentSum;
if (currentSum < target) left += 1;
else right -= 1;
}
}
return closestSum;
};