题目
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。
示例 2:
输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。
示例 3:
输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。
提示:
3 <= nums.length <= 3000
-105 <= nums[i] <= 105
解题思路
因为是三个数的和,那么就不好遍历了。首先得先固定一个数再去搜寻其他两个。但无论如何都得先排序吧
第一种
我想固定中间数,然后从这个数的两边开始遍历找和为0的元素。
实现是实现了,但是这种方法基本是要把所有情况都讨论一遍,没有可以提前退出的判断条件(如果有人想到了麻烦提醒我一下)
因此最终代码超时了
第二种
然后就是固定最小数,然后再这个数后面的数中选其他两个。这样的好处是肯定遍历的越来越少了,而且最小数>0之后就可以不用继续验证了,肯定凑不到0了
代码实现
这是超时了的方法,但也对了百分之九十多吧
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
n=len(nums)
ans=[]
for i in range(1,n-1):
left=i-1
right=i+1
for l in range(0,i):
for r in range(right,n):
if nums[i]+nums[l]+nums[r]==0 and [nums[i],nums[l],nums[r]] not in ans:
ans.append([nums[i],nums[l],nums[r]])
continue
return ans
这个是第二种,参考力扣某一解答思路
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
n=len(nums)
ans=[]
# 枚举 a
for first in range(n):
# 需要和上一次枚举的数不相同
if first > 0 and nums[first] == nums[first - 1]:
continue
# c 对应的指针初始指向数组的最右端
third = n - 1
target = -nums[first]
# 枚举 b
for second in range(first + 1, n):
# 需要和上一次枚举的数不相同
if second > first + 1 and nums[second] == nums[second - 1]:
continue
# 需要保证 b 的指针在 c 的指针的左侧
while second < third and nums[second] + nums[third] > target:
third -= 1
# 如果指针重合,随着 b 后续的增加
# 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])
return ans