3Sum Closest

这道题和3sum有些微的不同就在于,3sum是求所有满足要求的解,而这里只需要求得一个最精确的就行,所以查重在这里不是必要的逻辑了,而我们只需要对比三指针的和与target的差距和之前的最优解那个最好就行,下面是代码

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        base = 0
        n = len(nums)
        nums.sort()
        res = sys.maxint

        while base <= n - 3:
            a = nums[base]
            start, end = base + 1, n - 1
            while start <= end - 1:
                b, c = nums[start], nums[end]
                tmp = a + b + c
                if tmp == target:
                    return target
                elif tmp > target:
                    end -= 1
                else:
                    start += 1
                if abs(tmp - target) < abs(res - target):
                    res = tmp
            base += 1

        return res

results matching ""

    No results matching ""