题目来源:

https://leetcode.com/problems/3sum-closest/


题意分析:

这道题目输入一个数组nums和一个数target,找出数组中三个数,使得他们的和最接近target,返回这三个数的和。


题目思路:

这道题目和上一题3Sum很像,所以也可以用类似的方法去解决这个问题。整个过程分成两步:

①数组排序;这步时间复杂度是(O(nlogn))。

②固定一个数,这步的时间复杂度是(O(n))。

③在剩下的数里面通过“夹逼定理”,找出两个数,使得三个数的和最接近target。这步时间复杂度是(O(n))

总的时间复杂度为(O(nlogn) + O(n)*O(n)) = (O(n^2))。

优化:在第三步的时候通过判断剩下的数中是否最小的两个数相加就大于或者最大两个数就小于target - 第一个数,如果是,则直接判断最小(大)两个数和②中的那个数的和是不是最接近的值。


代码(python):

 class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
size = len(nums)
if size < 3:
return 0
nums.sort()
i = 0 # fix the first index
ans = nums[0] + nums[1] + nums[size - 1] # ans is used to record the solution
while i < size - 2:
tmp = target - nums[i]
j = i + 1
k = size - 1
while j < k:
if nums[j] + nums[k] == tmp:
return target
if nums[j] + nums[k] > tmp:
if nums[j] + nums[j + 1] >= tmp:
if nums[j] + nums[j + 1] - tmp < abs(ans - target):
ans = nums[i] + nums[j] + nums[j + 1]
break
tmpans = nums[i] + nums[j] + nums[k]
if tmpans - target < abs(ans - target):
ans = tmpans
k -= 1
else:
if nums[k] + nums[k - 1] <= tmp:
if tmp - nums[k] -nums[k - 1] < abs(ans - target):
ans = nums[i] + nums[k - 1] + nums[k]
break
tmpans = nums[i] + nums[j] + nums[k]
if target - tmpans < abs(ans - target):
ans = tmpans
j += 1
i += 1
if ans == target:
return target
return ans

转载请注明出处:http://www.cnblogs.com/chruny/p/4830175.html

[LeetCode]题解(python):016-3Sum Closest的更多相关文章

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

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

  2. No.016 3Sum Closest

    16. 3Sum Closest Total Accepted: 86565 Total Submissions: 291260 Difficulty: Medium Given an array S ...

  3. LeetCode--No.016 3Sum Closest

    16. 3Sum Closest Total Accepted: 86565 Total Submissions: 291260 Difficulty: Medium Given an array S ...

  4. [Leetcode][016] 3Sum Closest (Java)

    题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...

  5. 【LeetCode】016 3Sum Closest

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

  6. 【JAVA、C++】LeetCode 016 3Sum Closest

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

  7. [Leetcode]016. 3Sum Closest

    public class Solution { public int threeSumClosest(int[] num, int target) { int result = num[0] + nu ...

  8. 016 3Sum Closest 最接近的三数之和

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

  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 ...

  10. leetcode第16题--3Sum Closest

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

随机推荐

  1. php保留小数格式的多种方法

    php保留小数格式,定义小数格式,小数点,位数,小数位数: 方法一:(推荐)bcmul(1000.90,1,2);//两个数相乘1000.90*1, 保留两位小数点(无四舍五入)<返回strin ...

  2. js正则验证"汉字"

    var nickname = value; var regex = new RegExp("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){1 ...

  3. req.body取不到值的问题;

    随着express升级,bodyParser从express中被分离了出来,因此,在使用express新版本的时候,需要npm install body-parser 来安装bodyParser. 在 ...

  4. 超级密码(bfs)

    超级密码 Time Limit : 20000/10000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Total Submis ...

  5. 沙朗javascript(两)正则表达式

          以下提到的文章javascript基础,今天我说些什么javascript正则表达式正确.      说到这首先要问了,什么是正則表達式,正則表達式能干什么? 正則表達式:一个正則表達式就 ...

  6. Robolectric 探索之路

    layout: post title: Roboletric探索之路,从抗拒到依赖 description: Roboletric Android Unit Testing category: blo ...

  7. C/C++存储区划分

    一. 在c中分为这几个存储区1.栈 - 由编译器自动分配释放2.堆 - 一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收3.全局区(静态区),全局变量和静态变量的存储是放在一块的,初始化 ...

  8. .NET中的IO操作之文件流(一)

    读操作 //1.创建文件流 FileStream fsRead =new FileStream("1.txt",FileMode.Open); //2.创建缓冲区,正常情况下,是不 ...

  9. Oracle 奇葩的问题:创建存储过程没有反应

    问题描述:需要在oracle 数据库中再创建一个数据库(数据库实例)然后作为临时数据库,一切成功: 现在需要在数据库中新建一个表空间然后创建用户,使用创建的用户登录创建一个存储过程,执行提交刷新一下, ...

  10. Android 开发笔记 “Sqlite Cursor 使用”

    使用过 SQLite 数据库的童鞋对 Cursor 应该不陌生,如果你是搞.net 开发你大可以把Cursor理解成 Ado.net 中的数据集合相当于dataReader.今天特地将它单独拿出来谈, ...