LeetCode15. 三数之和
15. 三数之和
描述
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路
思路一
这种数值列表中有加减的题目,排序后可能会更加方便些。
固定两个数,将 target 设置为两个数之和的相反数,看 target 是否在列表中,若在,则为一个结果。
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret = []
# 数组题,其中有加减操作的,排序后会方便很多
nums.sort()
len_nums = len(nums)
for i in range(len_nums - 1):
for j in range(i+1, len_nums):
# 固定下来两个数,如果另外一个数也在数组中,则为一个结果
if -(nums[i]+nums[j]) in nums[j+1:]:
a_ret = [nums[i], nums[j], -(nums[i]+nums[j])]
if a_ret not in ret:
ret.append(a_ret)
return ret
但是这种方法有两层循环,果然报了 TLE(Time Limit Exceeded) 错误。
思路二
固定一个数,设置 target 为其他两个数之和的相反数,即 0 - 当前数,由两头向中间遍历数组,找到之和符合 target 的两个数即是一个结果。
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret = []
nums.sort()
for i in range(0, len(nums)):
# 若存在相同数,跳过以减少计算
if i > 0 and nums[i] == nums[i-1]:
continue
target = 0 - nums[i]
start, end = i+1, len(nums)-1
while start < end:
# 头尾之和大于目标值,尾向前移一位
if nums[start] + nums[end] > target:
end -= 1
# 头尾之和小于目标值,头向后移一位
elif nums[start] + nums[end] < target:
start += 1
# 头尾之和等于目标值,是一个结果,添加进去
# 头尾都移动一位
else:
ret.append([nums[i], nums[start], nums[end]])
start += 1
end -= 1
# 若移动后有重复值,继续移动
while start < end and nums[start] == nums[start-1]:
start += 1
while start < end and nums[end] == nums[end+1]:
end -= 1
return ret
GitHub地址:https://github.com/protea-ban/LeetCode

LeetCode15. 三数之和的更多相关文章
- Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数  先处理特殊情况,然后 先排序 注意不重复,只需要有 ...
- 南大算法设计与分析课程OJ答案代码(4)--变位词、三数之和
问题 A: 变位词 时间限制: 2 Sec 内存限制: 10 MB提交: 322 解决: 59提交 状态 算法问答 题目描述 请大家在做oj题之前,仔细阅读关于抄袭的说明http://www.bi ...
- LeetCode 15. 三数之和(3Sum)
15. 三数之和 15. 3Sum 题目描述 Given an array nums of n integers, are there elements a, b, c in nums such th ...
- [LeetCode] 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
- [LeetCode] 3Sum Closest 最近三数之和
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
随机推荐
- laravel tinker测试模型添加属性
php artisan tinker 新建一个模型对象 $post=new \App\Posts(); 给对象的属性挨个赋值 $post->title="this is title&q ...
- Chrome,firefox,ie等浏览器空格 宽度不一样
方案一:使用其他字符代替空格 使用( :)空格浏览器之间,显示的不一样,对不齐等现象. 解决方案: 用半角空格&ensp:或者全角空格&emsp:就可以了,&e ...
- c# 判断网络地址是否存在
方法一:网络地址存在,有可能可以访问,也有可能不能访问.此方法用来判断地址存在. static bool UrlIsExist(String url) { System.Uri u = null; t ...
- C语言实践 输出100以内的素数
int main() { int isprime = 1; for (int i = 2; i < 101; i++) { isprime = 1;//要确保每次循环都要把这个值设置为1,不然上 ...
- js日期 操作
//重写toString方法,将时间转换为Y-m-d H:i:s格式 Date.prototype.toString = function(){ ) + "-" + this.ge ...
- qt-vs-addin:Qt4和Qt5之VS插件如何共存与使用(转)
原则上,两者是不可以同时存在的,但是如果都安装了,该如何分别使用他们呢? Qt4 Visual Studio Add-in:官网可以下载安装程序,qt-vs-addin-1.1.11-opensour ...
- css总结6:行高和字体大小
1 CSS line-height 属性 代码: p.small {line-height:70%}p.big {line-height:200%} 运行后:70%与200%宽高 2 CSS font ...
- POJ2253 Frogger(spfa变形)
Description Freddy Frog is sitting on a stone in the middle of a lake. Suddenly he notices Fiona Fro ...
- c# 对象反射赋值未知属性需类型转换
反射某个类时,对于类的属性,字段.已知有已知的方法,未知有未知的写法. 而SetValues赋值则需要类型转换 情况1,该属性类型是已知类型,例如:int int value=500; propert ...
- Delphi XE8中Delphi和JAVA数据类型对应关系!
Delphi XE8中Delphi和JAVA数据类型对应关系所在单元文件:Androidapi.JNI.JavaTypes 对应关系: JObject = interface;//java.lang. ...