-
Notifications
You must be signed in to change notification settings - Fork 10
/
16_3sum-closest.js
68 lines (63 loc) · 1.8 KB
/
16_3sum-closest.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
*
* Problem:
* Given an array of unsorted numbers and a target number, find a triplet in the array
* whose sum is as close to the target number as possible, return the sum of the triplet.
* If there are more than one such triplet, return the sum of the triplet with the
* smallest sum.
* https://leetcode.com/problems/3sum-closest/
*
* Example 1:
* Input: [-2, 0, 1, 2], target=2
* Output: 1
* Explanation: The triplet [-2, 1, 2] has the closest sum to the target.
*
* Example 2:
* Input: [-3, -1, 1, 2], target=1
* Output: 0
* Explanation: The triplet [-3, 1, 2] has the closest sum to the target.
*
* Time: O(n^2) <- O(nlog(n)) + O(n^2)
* Space: O(n) <- merge sort
*
* Note: similar approach as 15_3sum.js, check there for detailed explanation.
*
* @param {number[]} array
* @param {number} targetSum
* @return {number}
*/
function tripletSumCloseToTarget(array, targetSum) {
// O(nlog(n))
array.sort((a, b) => a - b);
let minSum = Infinity;
// O(n)
for (let i = 0; i <= array.length - 3; i++) {
let left = i + 1;
let right = array.length - 1;
// O(n)
while (left < right) {
const sum = array[i] + array[left] + array[right];
if (sum === targetSum) {
return targetSum;
}
if (sum < targetSum) {
left++;
} else {
right--;
}
if (
// 1st condition: find the smallest diff
Math.abs(targetSum - sum) < Math.abs(targetSum - minSum) ||
// 2nd condition: find the smaller one if the diff are the same
(Math.abs(targetSum - sum) === Math.abs(targetSum - minSum) &&
sum < targetSum)
) {
minSum = sum;
}
}
}
return minSum;
}
// Test
console.log(tripletSumCloseToTarget([-2, 0, 1, 2], 2)); // 1
console.log(tripletSumCloseToTarget([-3, -1, 1, 2], 1)); // 0