-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16.最接近的三数之和.js
48 lines (47 loc) · 895 Bytes
/
16.最接近的三数之和.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
/*
* @lc app=leetcode.cn id=16 lang=javascript
*
* [16] 最接近的三数之和
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
let { length } = nums;
if (length < 3) {
return [];
}
nums.sort((a, b) => a - b);
let sum,
compare = Infinity;
for (let i = 0; i < length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
let j = i + 1,
k = length - 1,
candidate;
while (k > j) {
candidate = nums[i] + nums[j] + nums[k];
if (candidate === target) {
return nums[i] + nums[j] + nums[k];
} else {
let abs = Math.abs(candidate - target);
if (abs < compare) {
compare = abs;
sum = nums[i] + nums[j] + nums[k];
}
if (candidate > target) {
k--;
} else {
j++;
}
}
}
}
return sum;
};
// @lc code=end