[Leetcode] [Python]16:3sum Closest

Source: Internet
Author: User

#-*-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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.