三数之和
题目介绍
给你一个整数数组 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 。
思路梳理
解析:
如果我们将上个题目得指针解法称做是双指针的话,那么这个题目用到的方法就是三指针,因为我们是三数之和嘛,一个指针对应一个数,下面我们看一下具体思路,其实原理很简单,我们先将数组排序,直接 Arrays.sort() 解决,排序之后处理起来就很容易了。下面我们来看下三个指针的初始位置。
代码
题解1
多指针
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
nums.sort()
ans = list()
# 枚举 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
题解2
哈希表,但是这个会超时,不知道为什么,
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums = sorted(nums)
len_n = len(nums)
new_nums = nums[::-1]
for i in range(len_n):
if i >0 and nums[i] == nums[i-1]:
continue
for j in range(i+ 1, len_n):
if j != i+1 and nums[j] == nums[j-1]:
continue
k = 0 - nums[i] - nums[j]
if k in nums and (len_n-1-new_nums.index(k)) > j:
result.append([nums[i], nums[j], k])
return result