Open Tcdian opened 4 years ago
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
const sortedNums = [...nums].sort((a, b) => a - b);
let result = Infinity;
let difference = Infinity;
for (let i = 0; i < sortedNums.length - 2; i++) {
let left = i + 1;
let right = sortedNums.length - 1;
while (left < right) {
if (left > i + 1 && sortedNums[left] === sortedNums[left - 1]) {
left++;
continue;
}
if (right < sortedNums.length - 1 && sortedNums[right] === sortedNums[right + 1]) {
right--;
continue;
}
const sum = sortedNums[left] + sortedNums[right] + sortedNums[i];
if (Math.abs(sum - target) < difference) {
difference = Math.abs(sum - target);
result = sum;
}
if (sum === target) {
return sum;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
return result;
};
function threeSumClosest(nums: number[], target: number): number {
const sortedNums = [...nums].sort((a, b) => a - b);
let result = Infinity;
let difference = Infinity;
for (let i = 0; i < sortedNums.length - 2; i++) {
let left = i + 1;
let right = sortedNums.length - 1;
while (left < right) {
if (left > i + 1 && sortedNums[left] === sortedNums[left - 1]) {
left++;
continue;
}
if (right < sortedNums.length - 1 && sortedNums[right] === sortedNums[right + 1]) {
right--;
continue;
}
const sum = sortedNums[left] + sortedNums[right] + sortedNums[i];
if (Math.abs(sum - target) < difference) {
difference = Math.abs(sum - target);
result = sum;
}
if (sum === target) {
return sum;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
return result;
};
16. 3Sum Closest
给定一个包括
n
个整数的数组nums
和 一个目标值target
。找出nums
中的三个整数,使得它们的和与target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。Example
Note
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4