Topic
Three sum of the numbers II
to an array containing n integers, find and the ternary group closest to the given integer target, returning the number of the three numbers.
Sample Example
For example s = [-1, 2, 1,-4] and target = 1. And the ternary group closest to 1 is -1 + 2 + 1 = 2.
Note
You only need to return the sum of triples, without having to return the ternary group itself
Solving
Similar to the previous question, the program is only slightly modified
Public classSolution {/** * @paramnumbers:give An array numbers of n integer *@paramTarget:an Integer *@return: Return the sum of the three integers, the sum closest target. */ Public intThreesumclosest (int[] numbers,inttarget) { //Write your code here if(Numbers = =NULL) return0; Arrays.sort (numbers); intsum =Integer.max_value; intNumlen =numbers.length; for(inti = 0;i< Numlen; i++){ intleft = i + 1; intright = Numlen-1; while(Left <Right ) { intTmpsum = Numbers[i] + numbers[left] +Numbers[right]; intTmpdist = Tmpsum-Target; Sum= Math.Abs (tmpdist) > Math.Abs (sum-target)?sum:tmpsum; if(Tmpdist = = 0){ returnTarget; } if(Tmpdist <0) { left++; }Else{ Right--; } } } returnsum; }}
Java Code
Total time: 1504 Ms
classSolution:"""@param numbers:give An array numbers of n integer @param target:an integer @return: Return the sum of T He three integers, the sum closest target. """ defthreesumclosest (self, Numbers, target):#Write your code here ifNumbers = =None:return0 Numlen=len (Numbers) numbers.sort () sum=0 forIinchRange (numlen-1): Left= i + 1 Right= Numlen-1 whileLeft <Right:tmpsum= Numbers[i] + numbers[left] +Numbers[right] Tmpdist= Tmpsum-Targetifi==0:sum=tmpsum sum= SumifABS (Tmpdist) > abs (sum-target)ElseTmpsumifTmpdist = =0:returnTargetifTmpdist <0:left+=1Else: Right-=1returnSum
Python Code
Total time: 403 ms
Lintcode Medium Title: 3 Sum II three numbers and II