zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    正则表达式
    匿名函数作业
    内置函数&匿名函数
    模拟面试题一
    迭代器
    生成器
    装饰器
    函数
    疑问?
    3,app信息抽取
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10517890.html
Copyright © 2011-2022 走看看