我的解答:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
var min = Math.abs(nums[0] + nums[1] + nums[2] - target);
var result = null;
for (var i = 0; i < nums.length - 2; i++) {
for (var j = i + 1; j < nums.length - 1; j++) {
for (var k = j + 1; k < nums.length; k++) {
var sum = nums[i] + nums[j] + nums[k];
if (Math.abs(sum - target) <= min) {
min = Math.abs(sum - target);
result = sum;
}
}
}
}
return result;
};
时间复杂度是O(n3),需要想办法优化一下:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
var result = 0;
var closetValue = Infinity;
nums = nums.sort((a, b) => a - b);
for (var i = 0; i < nums.length - 2; i++) {
var l = i + 1;
var r = nums.length - 1;
while (l < r) {
var sum = nums[i] + nums[l] + nums[r];
var diff = Math.abs(sum - target);
if(diff < closetValue) {
result = sum;
closetValue = diff;
}
if (sum > target) {
r--;
} else if (sum < target) {
l++;
} else {
return sum;
}
}
}
return result;
};
利用双指针求解:时间复杂度为O(n2)