• 作者: 负雪明烛
  • 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 三数之和的更多相关文章

  1. [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 ...

  2. [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 ...

  3. 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 ...

  4. 【LeetCode 15】三数之和

    题目链接 [题解] 先把n个数字升序排个序. 然后枚举三元组最左边的那个数字是第i个数字. 之后用两个指针l,r移动来获取三元组的第2个和第3个数字. (初始值,l=i+1,r = n-1); 如果a ...

  5. [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 ...

  6. 【LeetCode】15、三数之和为0

    题目等级:3Sum(Medium) 题目描述: Given an array nums of n integers, are there elements a, b, c in nums such t ...

  7. LeetCode 第15题-三数之和

    1. 题目 2.题目分析与思路 3.思路 1. 题目 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且 ...

  8. LeeCode数组第15题三数之和

    题目:三数之和 内容: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中 ...

  9. 【LeetCode每天一题】3Sum(三数之和)

    Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...

随机推荐

  1. perl 子函数传入多个数组

    perl中的引用和C中的指针一样,用"\"标识,引用后可使用符号"->"取值.解引用则在对应的数据类型前加$,@ 或%. 这里这里用两数组求和做示例,引用 ...

  2. mysql—Linux系统直接进入mysql服务器,并实现一些基础操作

    首先,我们需要通过以下命令来检查MySQL服务器是否启动: ps -ef | grep mysqld 如果MySql已经启动,以上命令将输出mysql进程列表 如果mysql未启动,你可以使用以下命令 ...

  3. c/c++在线编译Output Limit Exceeded(OLE)错误

    提示输出错误,有如下两个可能情况: 1. 不符合题目给出的输出格式,自己输出了多余的内容或者格式不正确 2. 输入数据的时候,未考虑到输入错误的情况 针对2,有如下的例子: 错误的情况: 1 int ...

  4. 巩固javaweb第十二天

    巩固内容: HTML 图像- 图像标签( <img>)和源属性(Src) 在 HTML 中,图像由<img> 标签定义. <img> 是空标签,意思是说,它只包含属 ...

  5. 巩固javaweb第十六天

    巩固内容: 下拉框 在注册功能中,地区的选择使用了下拉框,可以从地区选项中选择一个地区.在这个 例子中,只允许选择一个,而在有些情况下,下拉框可以进行多选.所以,从功能上来说, 下拉框具有单选按钮和复 ...

  6. SELECT的语法

    我们先回顾下正则表达式.下图: 描述像xy, xxy (B上转一圈), xyy, xxyy这样的字符串.然后可以进行字符串匹配.设计芯片都用Verilog语言而不是画门电路了.像x+y+这样的叫做re ...

  7. eclipse上点击open Perspective找不到java EE的解决办法

    原因:没有安装java ee等插件 Help--->Install New software---->work  with中选择All Available  Sites---->  ...

  8. 零基础学习java------25--------jdbc

    jdbc开发步骤图 以下要用到的products表 一. JDBC简介 补充    JDBC本质:其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口,各个数据库厂商趋势线这个接口,提 ...

  9. 前端必须知道的 Nginx 知识

    Nginx一直跟我们息息相关,它既可以作为Web 服务器,也可以作为负载均衡服务器,具备高性能.高并发连接等. 1.负载均衡 当一个应用单位时间内访问量激增,服务器的带宽及性能受到影响, 影响大到自身 ...

  10. css相关,position定位详解

    CSS 有两个最重要的基本属性,前端开发必须掌握:display 和 position. display属性指定网页的布局.两个重要的布局,弹性布局flex和网格布局grid. 本文介绍非常有用的po ...