016 3SUM Closest

这道题与 015 3 SUM 基本思路一样 都是夹逼思想  复杂度 O(n*n)

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer}
    def threeSumClosest(self, nums, target):
        length = len(nums)
        nums = sorted(nums)
        ans = sum(nums[0:3])
        i = 0
        while i < length - 2:
            j = i + 1
            k = length - 1
            while j < k:
                s = nums[i] + nums[j] + nums[k]
                if s == target:
                    return target
                else:
                    if abs(ans - target) > abs(s - target):
                        ans = s
                    if s < target:
                        j += 1
                    else:
                        k -= 1
            i += 1
        return ans

 

posted @ 2015-07-08 06:15  dapanshe  阅读(85)  评论(0编辑  收藏  举报