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. 三数之和的更多相关文章

  1. Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合

    > 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数 ![在这里插入图片描述](https://img-blog.csdnimg.cn/63802fda72be45eba98d9e4 ...

  2. 【算法训练营day7】LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和

    [算法训练营day7]LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和 LeetCode454. 四数相加I ...

  3. [Swift]LeetCode15. 三数之和 | 3Sum

    Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...

  4. LeetCode15.三数之和 JavaScript

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  5. leetcode15 三数之和 双指针

    注意题目没要求数字只能用一次 a + b + c = 0 即为 -b=a+c,同时要求数字不全为正(然后发现a+b+c就行...不过多想想没坏处嘛) 先处理特殊情况,然后 先排序 注意不重复,只需要有 ...

  6. 南大算法设计与分析课程OJ答案代码(4)--变位词、三数之和

    问题 A: 变位词 时间限制: 2 Sec  内存限制: 10 MB提交: 322  解决: 59提交 状态 算法问答 题目描述 请大家在做oj题之前,仔细阅读关于抄袭的说明http://www.bi ...

  7. LeetCode 15. 三数之和(3Sum)

    15. 三数之和 15. 3Sum 题目描述 Given an array nums of n integers, are there elements a, b, c in nums such th ...

  8. [LeetCode] 3Sum Smaller 三数之和较小值

    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...

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

随机推荐

  1. 932F Escape Through Leaf

    传送门 题目大意 https://www.luogu.org/problemnew/show/CF932F 分析 我们可以从叶子向根每次插入b和ans 所以我们不难发现就是相当于插入线段 于是李超树+ ...

  2. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  3. 如何处理与开发有争议的Bug?

     工作中,测试人员有时会遇到类似的问题:提交了一份软件缺陷报告,可由于某种原因,无论是开发人员还是开发经理就是不愿修改程序.应如何处理这类问题呢?我认为,当对报告出现分歧意见后,测试工程师应首先做如下 ...

  4. css总结6:行高和字体大小

    1 CSS line-height 属性 代码: p.small {line-height:70%}p.big {line-height:200%} 运行后:70%与200%宽高 2 CSS font ...

  5. touchmove和touchend的使用

    touchstart:当手指触摸屏幕时触发:即使已经有一个手指放在了屏幕上也会触发.touchmove:当手指在屏幕上滑动时连续的触发.在这个事件发生期间,调用preventDefault()可阻止滚 ...

  6. android IntentService和ResultReceiver的异步处理

    IntentService和ResultReceiver的异步处理 1.在下载手机上从网络下载东西的时候会用到AsyncTask来方便处理,这里可以在用IntentService和ResultRece ...

  7. C# 多线程操作实例

    1.多线程操作 一旦打开线程就必须记得关闭 1.第一部分 这是个数字叠加小功能 private void CountTo(int countTo, CancellationToken ct) { ; ...

  8. WinForm中使用自定义Tooltip控件

    private ToolTip tooltipCtr; 构造函数中: 隐藏默认的Tooltip:this.ShowCellToolTips = false; this.tooltipCtr = new ...

  9. DFT到FFT的理解

    DFT简化计算理解(FFT)   DFT: WN=e^(-j*2*pi/N) DFT复杂度o(N^2) 降低与N^2的依赖 使N = LM  (L^2+m^2 <= N^2) N点DFT分解为M ...

  10. iOS应用审核时间注意点

    1.重大节假日不审核 美国重大节假日期间不审核,具体审核时间查看官方通知