leetcode 16-> 3Sum Closest

 

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.

class Solution(object):
    def threeSumClosest(self, nums, target):
        nums.sort()
        pre_sum = None
        for i in xrange(len(nums) - 2):
            head, tail = i+1, len(nums)-1
            while head < tail:
                sum = nums[i] + nums[head] + nums[tail]
                if pre_sum == None:
                    pre_sum = sum
                if abs(sum - target) < abs(pre_sum - target):
                    pre_sum = sum

                if sum < target:
                    head += 1
                elif sum > target:
                    tail -= 1
                else:
                    return target
        return pre_sum

 

posted @ 2019-03-12 16:57  anobscureretreat  阅读(121)  评论(0编辑  收藏  举报