Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
这题可以用暴力做,但时间复杂度是n^3的
还有一种方法是首尾指针逼近法:根据三个数的和来决定left和right的移动,效率比暴力高些
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
nums.sort((x, y) => x - y)
let close = Infinity
let len = nums.length
for(let i = 0; i < len - 2; i ++) {
let left = i + 1
let right = len - 1
while(left < right) {
let res = nums[i] + nums[left] + nums[right]
let cha = Math.abs(res - target)
let cha2 = Math.abs(close - target)
if(cha < cha2) close = res
if(res - target < 0) left ++
else if(res - target > 0) right --
else return target
}
}
return close
};
暴力:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
let len = nums.length
let res = 0, ans = 0
let close = Infinity
for(let i = 0; i < len - 2; i ++) {
for(let j = i + 1; j < len - 1; j ++) {
for(let z = j + 1; z < len; z ++) {
res = nums[i] + nums[j] + nums[z]
if(close > Math.abs(res - target)) {
close = Math.abs(res - target)
ans = res
if(!close) return target
}
}
}
}
return ans
};
an hour age 和 10 minutes ago 都是用暴力做的,区别仅仅是加了差值为0时,直接return target这个特判,没想到就快了很多
a few seconds ago是用首尾指针逼近做的