3Sum Closest
Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Analysis:
This is an upgraded version of topic 3Sum. Test instructions to find three elements in the given array a,b,c, so that A + B + C and the closest to the given target, return a + B + C.
The topic limits the three elements that must be found and unique.
Here we draw on the idea of 3Sum, or the array nums to sort, and then use a double pointer to traverse.
But unlike the previous question, the three elements we find here and generally do not equal target, if the three elements and nsum are greater than target, then the right pointer moves to the left, reducing the nsum value, and if the Nsum value is less than target, the left pointer moves to the right, increasing the Nsum value Of course, if Nsum equals target, then it's good to return directly to Nsum. The movement of two pointers allows the nsum to keep approaching target.
In the process of moving the pointer, we need to record the current difference between the nsum and target in real time, from which the nsum with the lowest absolute value of the difference is the closest to the target and the result.
The corresponding code is:
Class solution (Object): def threesumclosest (self, Nums, target): "" " : Type Nums:list[int] : Type Target:int : Rtype:int "" " DMin = float (' inf ') Nums.sort () for I in range (len (nums)-2): Left = i + 1 Right = Len (nums)-1 while left < right: nsum = Nums[left] + nums[right] + nums[i] if ABS ( Nsum-target) < ABS (DMin): dmin = nsum-target minsum = nsum if nsum > target: Right- = 1
if Nsum < target: Left + = 1 if nsum = = target: return nsum return minsum
Leetcode[array]----3Sum Closest