#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
16:3sum Closest
https://oj.leetcode.com/problems/3sum-closest/
Given an array S of n integers, find three integers in S such, the sum was closest to a Given 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).
===comments by dabay===
First sort, then fixed a number from left to right, in the back of the series using the left hand pointer toward the middle of the method to find.
When you are closer to target than before, update to find this value.
A number is fixed from left to right, and around two pointers move toward the middle.
‘‘‘
Class Solution:
# @return An integer
def threesumclosest (self, num, target):
If Len (num) < 3:
return []
Num.sort ()
closest = Num[0] + num[1] + num[2]
difference = ABS (target-closest)
For i in xrange (Len (num)-2):
J, k = i+1, Len (num)-1
While J < k:
sum = Num[i] + num[j] + num[k]
If ABS (Target-sum) < difference:
closest = Sum
difference = ABS (target-sum)
if sum = = target:
return sum
Elif Sum < target:
j = j + 1
Else
K = K-1
Return closest
def main ():
Sol = solution ()
Nums = [ -3,0,1,2]
Solution = Sol.threesumclosest (nums, 1)
Print Solution
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]16:3sum Closest