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 ...
随机推荐
- Java 基于quartz实现定时 之一(注解方式配置)
需要在项目里,导入quartz.jar package cn.zr.pringmvctest.trigger; import org.springframework.context.annotatio ...
- spring.net 集成nhibernate配置文件(这里暴露了GetCurrentSession 对于 CurrentSession unbond thread这里给出了解决方法)
我这里主要分成了两个xml来进行spring.net管理实际情况中可自己根据需要进行分类 Dao2.xml <?xml version="1.0" encoding=&quo ...
- 黑盒测试实践--Day1 11.25
黑盒测试实践--Day1 今天完成任务情况: 晚上得到老师布置的本周小组作业--黑盒测试的基本要求,然后小组在上周作业建立的微信群里开了个在线的短会,主要内容如下: 组长小靳带领大家学习了这个要求 计 ...
- Python 函数习题
#encoding=utf-8 from urllib.request import urlopen import random import os ''' 1. 定义一个fuc(url, folde ...
- Hyper-V和vmware在虚拟机中安装xen总结
1. Hyper-V 在hyper-v中安装了ubuntu13.04,运行很好,使用起来的效果感觉比vmware要舒服.安装变异xen的内核也没有问题,可以正常的安装,update-grub之后也可以 ...
- centos 升级 python
1. 下载python 2.7编译安装 $wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz $tar zxvf Python-. ...
- cad转shapefile文件
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1; private ESRI.ArcGIS.Controls.AxLicenseContr ...
- word 2013如何从某一页开始插入页码
把光标移入要插入页面的最前面 插入分页符 在要插入页码的页脚双击打开页脚设计 取消页脚和前面页眉的链接 插入页码
- vitamio MediaController总是显示在底部的问题
前面一直用腾讯的x5 tas来播放视频,但是体验效果不好,不能设置播放页,无法获取用户对视频的学习情况,百度了下,发现好多人在使用vitamio,最新版本是5.0的,下载可能要花费点时间,官网上竟然没 ...
- sqlserver中 多条数据合并成一条数据 (stuff 与 for xml path 连用)
SQL 列转行,即多行合并成一条 需求:按照分组,将多条记录内容合并成一条,效果如下: 数据库示例: CREATE TABLE [t2]([NID] [bigint] NULL,[district ...