• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Medium: 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.

Example:Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

二、思路

同前面的求三个数的和是否为1思路一样,这类基本上就是用两个指针,一个指头,一个指尾,然后根据条件来进行指针的移动。

 三、代码

#coding:utf-8
def threeSumClosest(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    closettarget = 0
    diff = float("inf")
    newnums = sorted(nums)
    for currentpoint in range(len(newnums)-2):
        leftpoint = currentpoint + 1
        rightpoint = len(newnums)-1
        while leftpoint < rightpoint:
            a = sum([newnums[currentpoint],newnums[leftpoint],newnums[rightpoint]])
            tmp = abs(target - a)
            if tmp < diff:
                closettarget = a
                diff = tmp
            if a < target:
                leftpoint+=1
            elif a > target:
                rightpoint-=1
            else:
                print(a)
                return a
    print(closettarget)
    return closettarget

if __name__ == '__main__':
    nums = [0,1,2]
    threeSumClosest(nums,3)

  



既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-04-16 23:44  乐晓东随笔  阅读(108)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3