题目:
解题思路与答案
双指针,在每得到一个sum值之后要和前一个较为接近的sum值比较。难点可能就在如何处理‘比较’这一块~
var threeSumClosest = function(nums, target) {
let length = nums.length;
nums.sort((a,b) => a - b);
let res = nums[0] + nums[1] + nums[length - 1]; //初始化第一个被比较的值
for(var i = 0; i < length - 2; i++){
if(i > 0 && nums[i] === nums[i - 1]) continue;
//去重是否会影响正确性?我感觉不会 加上去重效率快
let head = i + 1, end = length - 1;
while(head < end){
let sum = nums[i] + nums[head] + nums[end];
if(sum === target){
res = target;
break;
} else if (sum < target){
head++;
} else {
end--;
}
if(Math.abs(target - sum) < Math.abs(target - res)) { //更新比较值
res = sum;
}
}
}
return res;
};
Tip
(1). Math.abs()方法
//Math.abs(x) 函数返回一个数字的绝对值
//1.
Math.abs(-Infinity); // Infinity
Math.abs(-1); // 1
Math.abs(-0); // 0
Math.abs(0); // 0
Math.abs(1); // 1
Math.abs(Infinity); // Infinity
//2.Math.abs() 将其参数强制转换为数字。
// 无法强制转换的值将变成 NaN,使 Math.abs() 也返回 NaN。
Math.abs("-1"); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(""); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1, 2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN