【LeetCode】15. 3Sum 三数之和
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
- 个人公众号:负雪明烛
- 本文关键词:3sum, 三数之和,题解,leetcode, 力扣,Python, C++, Java
题目地址: https://leetcode.com/problems/3sum/description/
题目描述:
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
题目大意
在给定的数组中判断是否存在三个数的和是0,返回所有的组合,但是返回的组合中不能有重复。
解题方法
方法一:统计频率+双指针
我的做法和大多数人不一样,我看了很多人的做法是对原数组排序后进行的左右指针向中间合并。而我这个做法使用的是先进行次数统计、元素去重然后做的双指针。
我的这个思路是在923. 3Sum With Multiplicity中使用的,同样地两重循环,然后查找第三个值是否在给出的数字set中,然后判断3个数字相同的有多少,可能存在三个都相同,两个相同,三个都不同的情况,这个时候需要注意的是还需要对原来的数组中该数字出现的次数进行判断。另外题目说了防止同样的组合多次返回,那么我是用了一个笨方法就是用set保存已经使用了的组合,这样能判断是否已经出现过。
时间复杂度是O(N^2),空间复杂度是O(N)。看似操作复杂,实际上还是超过了48%的提交。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
count = collections.Counter(nums)
values = count.keys()
values.sort()
print(values)
N = len(values)
l, r = 0, N - 1
res = list()
visited = set()
for l in range(N):
for r in range(l, N):
t = 0 - values[l] - values[r]
if t in count:
if (t == 0 and count[t] >= 3) \
or (((t == values[l] and t != values[r]) or (t == values[r] and t != values[l])) and count[t] >= 2) \
or (l == r and values[l] != t and count[values[l]] >= 2) \
or (t != values[l] and t != values[r] and l != r):
curlist = sorted([values[l], t, values[r]])
finger = "#".join(map(str, curlist))
if finger not in visited:
res.append(curlist)
visited.add(finger)
return res
方法二:原数组排序+双指针
这个方法就是上面说的对原数组排序的做法,这个做法思路比较简单,对于排序后的数组遍历,对每个位置都从它的后一个元素和末尾一个元素向中间集中,如果和为0就添加到结果数组中。这里需要注意的地方是需要跳过相同的数字,因为同样的数字组合只能出现一次嘛。也就是两个while,注意判断相等的条件:i是向前面判断,j是向后面判断。
这个方法不用使用set来保存已经遍历过的数字组合,因为对于原数组来说每次向后遍历的过程中,同样的组合只能出现一次。
时间复杂度是O(N^2),空间复杂度是O(1)。代码很清晰简短,实际上只超过了24%的提交。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
N = len(nums)
nums.sort()
res = []
for t in range(N - 2):
if t > 0 and nums[t] == nums[t - 1]:
continue
i, j = t + 1, N - 1
while i < j:
_sum = nums[t] + nums[i] + nums[j]
if _sum == 0:
res.append([nums[t], nums[i], nums[j]])
i += 1
j -= 1
while i < j and nums[i] == nums[i - 1]:
i += 1
while i < j and nums[j] == nums[j + 1]:
j -= 1
elif _sum < 0:
i += 1
else:
j -= 1
return res
参考资料:
日期
2018 年 10 月 17 日 —— 今又重阳,战地黄花分外香
【LeetCode】15. 3Sum 三数之和的更多相关文章
- [LeetCode] 15. 3Sum 三数之和
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- [leetcode]15. 3Sum三数之和
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...
- leetCode 15. 3Sum (3数之和) 解题思路和方法
3Sum Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find ...
- 【LeetCode 15】三数之和
题目链接 [题解] 先把n个数字升序排个序. 然后枚举三元组最左边的那个数字是第i个数字. 之后用两个指针l,r移动来获取三元组的第2个和第3个数字. (初始值,l=i+1,r = n-1); 如果a ...
- [LeetCode] 3Sum 三数之和
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- 【LeetCode】15、三数之和为0
题目等级:3Sum(Medium) 题目描述: Given an array nums of n integers, are there elements a, b, c in nums such t ...
- LeetCode 第15题-三数之和
1. 题目 2.题目分析与思路 3.思路 1. 题目 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且 ...
- LeeCode数组第15题三数之和
题目:三数之和 内容: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中 ...
- 【LeetCode每天一题】3Sum(三数之和)
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...
随机推荐
- 卷积神经网络(Convolutional Neural Networks)CNN
申明:本文非笔者原创,原文转载自:http://www.36dsj.com/archives/24006 自今年七月份以来,一直在实验室负责卷积神经网络(Convolutional Neural ...
- 07 MySQL安装图解--Windows版本
MySQL安装图解 使用微信扫码关注微信公众号,并回复:"MySQL环境",免费获取下载链接! 1.安装MySQL 2.校验MySQL 3.登录MySQL 登录MySQL:mysq ...
- RocketMQ这样做,压测后性能提高30%
从官方这边获悉,RocketMQ在4.9.1版本中对消息发送进行了大量的优化,性能提升十分显著,接下来请跟着我一起来欣赏大神们的杰作. 根据RocketMQ4.9.1的更新日志,我们从中提取到关于消息 ...
- javaSE高级篇1 — 异常与多线程基础
1.异常的体系结构 注:Throwable是一个类,不是一个接口,这个类里面是描述的一些Error和Exception的共性,如图所示: 异常 / 错误是什么意思? 定义:指的是程序运行过程中,可能 ...
- c/c++在线编译Output Limit Exceeded(OLE)错误
提示输出错误,有如下两个可能情况: 1. 不符合题目给出的输出格式,自己输出了多余的内容或者格式不正确 2. 输入数据的时候,未考虑到输入错误的情况 针对2,有如下的例子: 错误的情况: 1 int ...
- 巩固java第四天
巩固内容: HTML 元素 HTML 文档由 HTML 元素定义. HTML 元素 开始标签 * 元素内容 结束标签 * <p> 这是一个段落 </p> <a href= ...
- 『学了就忘』Linux文件系统管理 — 67、通过命令模式进行LVM分区
目录 1.物理卷管理 (1)准备硬盘或者分区 (2)建立物理卷 (3)查看物理卷 (3)删除物理卷 2.创建卷组 (1)建立卷组 (2)查看卷组 (3)增加卷组容量 (4)减小卷组容量 (5)删除卷组 ...
- 输入URL展示过程
一. 输入URL,回车 敲击某个键时,键盘内的处理器会先对键矩阵进行分析,然后将数据发送到计算机 计算机接收到来自键盘的信号,由键盘控制器(一种集成电路)进行处理,发送给操作系统 操作系统会分析,这些 ...
- 【JavaWeb安全】RMI-Remote Method Invocator
RMI-Remote Method Invocator 什么是RMI?RMI有什么用? RMI允许用户通过数据传输,调用远程方法,在远程服务器处理数据.例如将1,3传到远程服务器的加法运算器,加法运算 ...
- 容器之分类与各种测试(四)——unordered-multiset
unordered-multiset是不定序关联式容器,其底部是通过哈希表实现功能. (ps:黑色框就是bucket,白色框即为bucket上挂载的元素) 为了提高查找效率,bucket(篮子)的数量 ...