/ * *

The title

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:

Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The closest sum to target is 2 (-1 + 2 + 1 = 2). Tip:

3 <= nums.length <= 10^3

-10^3 <= nums[i] <= 10^3

-10^4 <= target <= 10^4

Source: LeetCode link: leetcode-cn.com/problems/3s… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

The test code

Print (threeSumClosest ([1, 2, 1, 4], 1))

notes

The violent solution is a triple cycle

Another way to think about it is sort + double pointer sort the array first and then select a baseline I = 0, so in the outer loop I += 1 left = I + 1 right = count – 1

Inner loop: when left < right, calculate the sum of the three indexes. If the sum is greater than the target value, then the right boundary is moved forward. If the sum is less than the target value, then the left boundary is moved backward

There are three other efficiency tips: 1 check that the number of arrays is equal to 3; 2 Repeat elements skip the calculation; 3 Loop in the current sum is equal to the target value directly return

The code address

Github.com/zmfflying/Z… * /

The problem solving code

import Foundation func threeSumClosest(_ nums: [Int], _ target: Var left = 1 var right = count - 1 var left = 1 var right = count - 1 If count == 3 {return nums[I] + nums[left] + nums[right] Sorted () var res = sortedNums[I] + sortedNums[left] + sortedNums[right] while I < count - 2 If I > 0 && sortedNums[I] == sortedNums[I -1] {I += 1 continue} left = I + 1 right = count -1 while left < Right {let cur = sortedNums[I] + sortedNums[left] + sortedNums[right] // If the current value is less than the target value, the left border is moved back } else if cur > target {// right -= 1} else {return (cur) Abs (target - cur) < abs(target - res) {res = cur}}Copy the code