-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy paththree_sum_closest.js
More file actions
31 lines (29 loc) · 882 Bytes
/
three_sum_closest.js
File metadata and controls
31 lines (29 loc) · 882 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
var threeSumClosest = function (nums, target) {
// Sort the array
nums.sort((a, b) => a - b);
// Length of the array
const n = nums.length;
// Result
let closest = nums[0] + nums[1] + nums[n - 1];
// Loop for each element of the array
for (let i = 0; i < n - 2; i++) {
// Left and right pointers
let j = i + 1;
let k = n - 1;
// Loop for all other pairs
while (j < k) {
let sum = nums[i] + nums[j] + nums[k];
if (sum <= target) {
j++;
} else {
k--;
}
if (Math.abs(closest - target) > Math.abs(sum - target)) {
closest = sum;
}
}
}
return closest;
};
console.log(threeSumClosest([-1, 2, 1, -4], 1));
console.log(threeSumClosest([2, 3, 7, 1, 5, 7, 1, 8, -1, -4, -4, 3], 12))