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 ...
随机推荐
- PHP Liunx 服务安全防范方案
PHP100平均每个月都会有入侵或者攻击,我们做了很多工作,当然很多高手们还是可以入侵,这我们并不感到奇怪,因为我们相信天外有天,人外有人,虽然 我们现在服务器还是稳定(高手们不要来喷了),我们把我们 ...
- vim 的移动
越来也喜欢用linux的vim 来编程了,简单.高效.专业,最近拿着一本<vim的中文使用手册>在慢慢的看,看到现在就没有勇气继续看下去,我想先放一下,运用前面自己学的东西实际的去操作一下 ...
- Opennebula自定义VM 实现方法-Contextualizing Virtual Machines 2.2
from:http://archives.opennebula.org/documentation:archives:rel2.2:cong There are two contextualizati ...
- win32多线程 (四) Mutex
Mutex 用途和critical section 非常类似,不过Mutex是内核对象,速度比section慢.Mutexes可以跨进程使用.另外Mutex在等待的时候可以设置等待时间. 以下是两种 ...
- CentOS7虚拟机安装Linux教程及安装后所遇到的问题
1.VMware Workstation15下载. 官方链接:http://download3.vmware.com/software/wkst/file/VMware-workstation-ful ...
- glib hash库GHashTable的使用实例
前言 hash表是一种key-value访问的数据结构,hash表存储的数据能够很快捷和方便的去查询.在很多工程项目都需要使用到hash表来存储数据.对于hash表的详细说明这里就不进行阐述了,不了解 ...
- Entity Framework 6.0 Tutorials(9):Stored Procedure Mapping
Code First - Insert, Update, Delete Stored Procedure Mapping: Entity Framework 6 Code-First provides ...
- datagrid 自定义 pager
$(document).ready(function(){ var p = $('.easyui-datagrid').datagrid('getPager'); $(p).pagination({ ...
- (转)使用Jquery+EasyUI 进行框架项目开发案例讲解之一 员工管理源码分享
原文地址:http://www.cnblogs.com/huyong/p/3334848.html 在开始讲解之前,我们先来看一下什么是Jquery EasyUI?jQuery EasyUI是一组基于 ...
- orcl 对table的一些操作
删除 table:drop table 表名: 恢复删除 : flashback table 表名 to before drop: 清空table : truncate table 表名; 恢复清空: ...