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 ...
随机推荐
- 多重if else和switch case的区别
int main(void) { int id; scanf_s("%d",&id); switch(id) { case 2: printf("John\n&q ...
- Linux cmus
一.简介 CMus 是一款类似于MOC, Herrie 或 mp3blaster 的基于终端的音乐播放器,支持 Ogg Vorbis, FLAC, MP3, WAV, Musepack, WavPac ...
- pymysql模块使用---Python连接MySQL数据库
pymysql模块使用---Python连接MySQL数据库 浏览目录 pymysql介绍 连接数据库 execute( ) 之 sql 注入 增删改查操作 进阶用法 一.pymysql介绍 1.介绍 ...
- css总结16:HTML5 多媒体音频(Audio)视频(video )
1 显示嵌入网页中的 MP3 文件: <embed height="50" width="100" src="horse.mp3"&g ...
- jquery中attr和prop的区别(转)
在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别?这些问题就出现了. 关于它们两个的区别,网上的答案很多.这里谈谈我的心得,我的心得很简单: ...
- java中为什么要使用代理
引入代理: 我们为什么要引入java的代理,除了当前类能够提供的功能外,我们还需要补充一些其他功能. 最容易想到的情况就是权限过滤,我有一个类做某项业务,但是由于安全原因只有某些用户才可以调用这个类, ...
- MVC 登陆鉴权
public ActionResult Login(string data) { var _params = JsonConvert.DeserializeAnonymousType(data, ne ...
- 分享我的第一个asp.net core开发过程
.net core 这个东西感觉还是很不错的,学习了一下,并且做了一个微服务(IP地址查询服务) http://vju.cc/ip/ipquery 看上他的跨平台功能,所以就研究一下,中间有不少坑,有 ...
- Educational Codeforces Round 62 (Rated for Div. 2)E(染色DP,构造,思维,组合数学)
#include<bits/stdc++.h>using namespace std;const long long mod=998244353;long long f[200007][2 ...
- 洛谷P4724 【模板】三维凸包
题面 传送门 题解 先理一下关于立体几何的基本芝士好了--顺便全都是从\(xzy\)巨巨的博客上抄来的 加减 三维向量加减和二维向量一样 模长 \(|a|=\sqrt{x^2+y^2+z^2}\) 点 ...