题目内容
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
https://leetcode-cn.com/problems/3sum/
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
题目思路
这道题目的要求在于找到3个和为0的数字组合。题目本身并不难,可以考虑先找到一个数字,然后简化成找到2个数字组合的问题。但是当给定的nums非常大时,效率会变得很低。所以可以对查找方式和输出进行优化。
要求3个数字的和为0,所以除非是全0,否则至少有1个负数。因而组合只可能有两种情况:[0,0,0]和[正数,负数,正/负数]
我们可以把数字分拣到正数数组和负数数组进行查找。在输出结果的时候,为了避免重复输出,我们可以要求k=-(i+j)的k是i,j中间的那个数时才添加到队尾。
程序代码
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
count={}
res=[]
for i in set(nums):
count[i]=nums.count(i)
if 0 in nums and count[0]>=3:
res.append([0,0,0])
positive=[i for i in count if i>0]
negative=[i for i in count if i<0]
for i in positive:
for j in negative:
k=-(i+j)#为了节约时间,我们可以规定K必须是在i,j中间的那个数时才插入。
if k in count:
if j<k<i or ((k==i or k==j) and count[k]>=2):
res.append([j,k,i])
return res