首页 > 其他 > 详细

leetcode 16-> 3Sum Closest

时间:2019-03-12 17:07:36      阅读:156      评论:0      收藏:0      [点我收藏+]

 

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

 

leetcode 16-> 3Sum Closest

原文:https://www.cnblogs.com/sea-stream/p/10517890.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!