leetcode 16-> 3Sum Closest


Given an arraynumsofnintegers and an integertarget, find three integers innumssuch that the sum is closest totarget. 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

优质内容筛选与推荐>>
1、★宣传广告变成社会标准
2、【c++ primer读书笔记】【第7章】类
3、maven排除jar包冲突
4、随意组合 dfs
5、加载ralink固件rt73.bin


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号