Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 34 35 36 37 38 | 5x 5x 41x 5x 8x 8x 8x 19x 19x 3x 16x 16x 13x 13x 16x 14x 2x 2x | import { MAX_INT } from './utils'
export default function threeSumClosest(
nums: number[],
target: number,
): number {
let solution = 0
let distance = MAX_INT
nums.sort((a, b) => a - b)
for (let i = 0; i < nums.length - 2; i++) {
let j = i + 1
let k = nums.length - 1
while (j < k) {
const curSum = nums[i] + nums[j] + nums[k]
if (curSum === target)
return curSum
const curDistance = Math.abs(target - curSum)
if (curDistance < distance) {
distance = curDistance
solution = curSum
}
if (curSum < target)
j++
else
k--
}
}
return solution
}
|