Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Topic describes

Given an array of n integers nums and a target value target. Identify the three integers in NUMs so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs.

  • Example:
Enter nums = [-1.2.1, -4], target = 1Output:2Explanation: The sum closest to target is2 (-1 + 2 + 1 = 2).Copy the code
  • Tip:
`3 <= nums.length <= 10^3`
`-10^3 <= nums[i] <= 10^3`
`-10^4 <= target <= 10^4`
Copy the code

Implementation approach

When I see the sum of several numbers, my first thought is that I want to sort the array, and then use a double pointer. The difference is that there is an extra number, but it doesn’t affect me very much. We can completely iterate through the array to cancel out the number. Array increment sort, traversal the number of each number in the array with a double pointer to point to the head and tail of the array, through the array traversal and pointer walk to change the three numbers record the sum of the three, compared to leave the sum of the three closest to the target.

/ * * *@param {number[]} nums
 * @param {number} target
 * @return {number}* /
var threeSumClosest = function(nums, target) {
    nums = nums.sort((x, y) = > x - y)
    let sum = nums[0] + nums[1] + nums[2]
    nums.forEach((item, index) = > {
        let li = 0 / / the head pointer
        let ri = nums.length - 1 / / the tail pointer
        while (li < ri) { // when the first and last Pointers meet, run through the next number
            if (li==index) {
                li++
                continue
            }
            if (ri==index) {
                ri--
                continue
            }
            let itemSum = item + nums[li] + nums[ri]  // The sum of three numbers
            if (itemSum < target) { // If the number of bytes is smaller than the target, the pointer moves to the right; if the number of bytes is larger than the target, the pointer moves to the left
                li++
            } else {
                ri--
            }
            sum = Math.abs(target - itemSum) < Math.abs(target - sum) ? itemSum : sum // Leave the number closest to the target}})return sum
};
Copy the code