Problem
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:
1 | |
Explanation
- Similar to 15. 3Sum, first, sort the array. We need to fix one number, then use two pointers technique to find the sum of 3 elements, and compare the sum with the target to get the
newDiff. Since we are looking for the closest sum, we need to define adiffvariable as the minimum diff. In other words, ifnewDiffis less thandiff, then updatedifftonewDiff. Note, we should use absolute value to findnewDiff.
Solution
1 | |