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. ZOJ3954 Seven-Segment Display

    题意: emmmm见原题吧 分析: 这也是当时省赛选拔的题,场上以为是大模拟,然后没敢写...补题发现是道水题··· 因为每一列的顺序不一定,但是行是一定的.所以只要把每一列组成一个数字,然后弄两个集 ...

  2. shell 别名alias

    在这说下 shell   命令 alias 别名   看个人爱好 设置. 直接执行命令  显示当前所有别名 alias  别名='新的别名'  该命令在当窗口关闭以后 会失效  想要永久生效  需要在 ...

  3. WEB前端--JavaScript

    JavaScript JavaScript基础 一.JavaScript简介 JavaScript是一种嵌入到HTML文件中的描述性语言,由浏览器的解释器将其动态地处理成可执行的代码,能独立地完成与客 ...

  4. 10.Execution failed with exit status: 3

    错误信息: insert overwrite table t_mobile_mid_use_p_tmp4_rcf select '201411' as month_id, a.prov_id, a.c ...

  5. 用conda创建一个tensorflow 虚拟环境

    创建your——user——name = tensorflow 的虚拟环境 xinpingdeMacBook-Pro:~ xinpingbao$ conda create -n tensorflow ...

  6. Android onKeyDown、onKeyUp、dispatchKeyEvent的区别

    1. onKeyDown.onKeyUp.dispatchKeyEvent的区别和使用场景 区别: 1.1 onKeyDown.onKeyUp是按键事件的回调接口(冒泡式调用),dispatchKey ...

  7. CentOS6.5 Eclipse C++ 版本 OpenCV

    最近在搞Linux上用Eclipse(C++版本)开发 OpenCV,配环境配的那真是配到天昏地暗,不知所措,好在配成功了,期间参考了大量的帖子,所以,特立此贴,希望能给后来人一些小建议! 1.Cen ...

  8. HttpUploader7-授权码配置

    1.1. 七牛云存储 配置方式: 1.配置授权码   2.配置云存储   3.配置空间名称   4.配置上传地址   1.2. 阿里云存储 配置方式: 1.填写授权码   2.配置云存储为阿里云   ...

  9. CSS3的2D与3D转换

    2D和3D转换涉及到数学中的知识,作为一个数学专业的毕业生,不研究一下岂不是对不起自己的专业? 首先来看几个参数: 1.transform-origin:origin(起源,起点),也即变形的起点,在 ...

  10. XE下 SVG格式的图标使用方法

    下载一个SVG格式的图标,千图网,http://tool.58pic.com/tubiaobao/ 用txt文本打开SVG图标 拖一个PathLabel控件 在PathLabel控件的Data属性添加 ...