16. 3Sum Closest
题目:
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的更多相关文章
- [LeetCode][Python]16: 3Sum Closest
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 16: 3Sum Closesthttps://oj.leetcode.com ...
- LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum
n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...
- 《LeetBook》leetcode题解(16):3Sum Closest [M]
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- 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 ...
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- Leetcode 16. 3Sum Closest(指针搜索)
16. 3Sum Closest Medium 131696FavoriteShare Given an array nums of n integers and an integer target, ...
- 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 = ...
- [LeetCode] 16. 3Sum Closest 最近三数之和
Given an array nums of n integers and an integer target, find three integers in nums such that the s ...
- 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 ...
随机推荐
- 【原】关于使用sklearn进行数据预处理 —— 归一化/标准化/正则化
一.标准化(Z-Score),或者去除均值和方差缩放 公式为:(X-mean)/std 计算时对每个属性/每列分别进行. 将数据按期属性(按列进行)减去其均值,并处以其方差.得到的结果是,对于每个属 ...
- 图解Javascript原型链
本文尝试阐述Js中原型(prototype).原型链(prototype chain)等概念及其作用机制.上一篇文章(图解Javascript上下文与作用域)介绍了Js中变量作用域的相关概念,实际上关 ...
- 微信JS接口
微信JS接口 分享到朋友圈 分享给朋友 分享到QQ 拍照或从手机相册中选图 识别音频并返回识别结果 使用微信内置地图查看位置来源:http://www.cnblogs.com/txw1958/p/ ...
- Ubuntu操作系统相关
1.安装 三种网络类型 修改密码 重启unbuntu系统,出现starting启动界面后,长按shift键. 出现如下引导界面: (注意:这里保持默认的选项就行,即白色横条选择在*Ubuntu上,不要 ...
- codevs 2988 保留小数 2
2988 保留小数 2 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 白银 Silver 题目描述 Description 这个难度是吸引你点进来的.(其实难度挺 ...
- 【Beta】Scrum03
Info 时间:2016.12.01 21:30 时长:15min 地点:大运村1号公寓5楼楼道 类型:日常Scrum会议 NXT:2016.12.04 21:30 Task Report Name ...
- 10月24日下午PHP封装
class Ren { private $name; private $sex; private $age;//年龄必须在18-50岁之间 function __construct($n) { $th ...
- 面试题目——《CC150》数组与字符串
面试题1.1:实现一个算法,确定一个字符串的所有字符是否全都不同.假使不允许使用额外的数据结构,又该如何处理? 注意:ASCII字符共有255个,其中0-127的字符有字符表 第一种解法:是<C ...
- [Unity3D]导入模型并且设置相应的属性
将资源拷贝到Assets中并设置 首先确保法线贴图的属性如下: 设置基本贴图和法线贴图 因为要发布到移动端,设置shader属性: 为了设置更好的反光效果,添加cubemap: 添加新的Materia ...
- margin双边距的问题
margin:20px;height:20px;float:left margin:20px;height:20px;float:left