forked from zzxboy1/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum_Closest.js
More file actions
33 lines (33 loc) · 840 Bytes
/
3Sum_Closest.js
File metadata and controls
33 lines (33 loc) · 840 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
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
nums.sort(function(a, b) {
return a - b;
});
var result = null,
len = nums.length;
for (var i = 0; i < len; i++) {
if (nums[i] === nums[i - 1]) {
continue;
}
var low = i + 1,
high = len - 1;
while (low < high) {
var sum = nums[low] + nums[high] + nums[i];
if (sum === target) {
return target;
} else if (sum < target) {
low++;
} else {
high--;
}
if (result === null || Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
}
}
return result;
};