-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathres.js
49 lines (42 loc) · 1.05 KB
/
res.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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-05-17 09:40:45
*
* Solution: https://discuss.leetcode.com/topic/1978/a-n-2-solution-can-we-do-better/2
*
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
let threeSumClosest = function(nums, target) {
let len = nums.length;
if (len < 3) {
return nums.reduce(reduceArray, 0);
}
nums.sort(compareNumbers);
function compareNumbers(a, b) {
return a - b;
}
function reduceArray(a, b) {
return a + b;
}
let res = nums[0] + nums[1] + nums[2];
for (let i = 0; i < len - 2; i++) {
let j = i + 1,
k = len - 1;
while (j < k) {
let sum = nums[i] + nums[j] + nums[k];
if (Math.abs(res - target) > Math.abs(sum - target)) {
if (sum === target) return target;
res = sum;
}
if (sum > target) {
k--;
} else {
j++;
}
}
}
return res;
};