题目:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

代码:

做过第15题:3Sum之后,看到该问题,不会很陌生,只不过这次目标值不在是0,而是尽可能接近一个传入的参数

同样先尝试了遍历3遍,也就是O(n^3)时间复杂度,不出所料,超时。

于是,根据上一题的经验,先确定第一个数字,之后在剩余数字中定义两端的两个指针,一个最大一个最小,根据三数相加和目标值比较的结果,分别移动左右两端的指针,增加或缩小三数的和,靠近目标值。

代码已经加入详细注释,根据之前的经验自己写的,调试了很久。还有很多不足,共同学习,望大神多多指教:

def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if len(nums) < 3: return 0
        #排序
        nums.sort()
        res = 0
        result = []
        flag = []
        length = len(nums)
        for i in range(0, length - 2):
            if i and nums[i] == nums[i - 1]:
                continue
            left, right = i + 1, length - 1
            while left < right:   
                #如果三数字相加结果等于目标值,直接返回结果
                if nums[i] + nums[left] + nums[right] == target:
                    #print(left,right, "equal ",nums[i], nums[left],  nums[right])
                    res = target
                    return res
                #如果三数字相加结果大于目标值,右边的数字指针减小
                elif nums[i] + nums[left] + nums[right] > target:
                    print(left,right, "big ",nums[i], nums[left],  nums[right])                      
                    res =  nums[i] + nums[left] + nums[right]
                    right -= 1
                    #如果指针指向的下一个数字和该数字相同,则指针继续向左移动
                    while left < right and nums[right]==nums[right+1]:
                        right -= 1
                    #由于存在移动一位之后三数字相加和突然小于目标值的情况,所以需要记录该值来比较
                    #否则下一轮循环之后的值和目标值得差可能比当前更大
                    if nums[i] + nums[left] + nums[right] < target:
                        result.append(res)
                        flag.append(abs(res-target))   
                #如果三数字相加结果小于目标值,左边的数字指针增加        
                else:
                    print("little ",nums[i], nums[left],  nums[right])                  
                    res =  nums[i] + nums[left] + nums[right]
                    left += 1
                    #如果指针指向的下一个数字和该数字相同,则指针继续向右移动
                    while left < right and nums[left]==nums[left-1]:
                        left += 1
                    #由于存在移动一位之后三数字相加和突然大于目标值的情况,所以需要记录该值来比较
                    #否则下一轮循环之后的值和目标值得差可能比当前更大
                    if nums[i] + nums[left] + nums[right] > target:
                        result.append(res)
                        flag.append(abs(res-target))   
            #result分别存储不同的第一个数字遍历后最接近目标值的结果
            #flag对应存储不同结果和目标值之间的差
            result.append(res)
            flag.append(abs(res-target))
        print (result,'\n',flag)
        #返回差距最小的结果即可    
        return (result[flag.index(min(flag))])

16. 3Sum Closest的更多相关文章

  1. [LeetCode][Python]16: 3Sum Closest

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 16: 3Sum Closesthttps://oj.leetcode.com ...

  2. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  3. 《LeetBook》leetcode题解(16):3Sum Closest [M]

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  4. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  5. LeetCode 16. 3Sum Closest(最接近的三数之和)

    LeetCode 16. 3Sum Closest(最接近的三数之和)

  6. Leetcode 16. 3Sum Closest(指针搜索)

    16. 3Sum Closest Medium 131696FavoriteShare Given an array nums of n integers and an integer target, ...

  7. 15. 3Sum、16. 3Sum Closest和18. 4Sum

    15 3sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = ...

  8. [LeetCode] 16. 3Sum Closest 最近三数之和

    Given an array nums of n integers and an integer target, find three integers in nums such that the s ...

  9. Leetcode 16. 3Sum Closest

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

随机推荐

  1. Django用已有的数据库

    python mysite/manage.py inspectdb  会按照你的数据库生成Model  拷贝进去用就可以了!

  2. mui事件绑定和可以用的js dom操作方法

    <script> //事件绑定 对象 方法 子元素 回调函数 mui('body').on('shown', '.mui-popover', function(e) { //console ...

  3. java连接mysql

    Java 连接 MySQL 需要驱动包,最新版下载地址为:http://dev.mysql.com/downloads/connector/j/,解压后得到jar库文件,然后在对应的项目中导入该库文件 ...

  4. a版本冲刺第一天

    队名:Aruba   队员: 黄辉昌 李陈辉 林炳锋 鄢继仁 张秀锋 章  鼎 学号 昨天完成的任务 今天做的任务 明天要做的任务 困难点 体会 408 学习测试文档的编写 继续学习并借鉴,开始着手写 ...

  5. 用Python制作新浪微博爬虫

    早上刷空间发现最近好多人过生日诶~ 仔细想想,好像4月份的时候也是特别多人过生日[比如我 那么每个人生日的月份有什么分布规律呢...突然想写个小程序统计一下 最简单易得的生日数据库大概就是新浪微博了: ...

  6. RabbitMQ Lazy Queue 延迟加载

    Lazy Queue 在著名的单例设计模式中就有懒汉式的实现方式,也就是只有在你需要的时候我才去加载. 这让博主想到了以前上学的时候,每到了假期的假期作业,在假期的时候是从来不做的.只有在快开学老师要 ...

  7. python面向对象进阶(八)

    上一篇<Python 面向对象初级(七)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...

  8. PDFobject插件使用,PDF在线查看插件

    1.引入插件JS <script type="text/javascript" src="PDFobject.js"></script> ...

  9. [转]js获取域名、url、url参数值

    //获取域名host1 = window.location.host;host2 = document.domain; //获取页面完整地址url = window.location.href; 获取 ...

  10. 高版本api在低版本中的兼容

    直接上例子,看如何避免crash. eg:根据给出路径,获取此路径所在分区的总空间大小. 文档说明:获取文件系统用量情况,在API level 9及其以上的系统,可直接调用File对象的相关方法,以下 ...