我的个人微信公众号:Microstrong
微信公众号ID:MicrostrongAI
微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!
知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities
15. 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.
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] ]
解题思路:
(1)暴力解法
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
length = len(nums)
res = []
seen = set()
for i in range(length):
for j in range(length):
if i == j:
continue
for k in range(length):
if j == k:
continue
if i == k:
continue
if nums[i] + nums[j] + nums[k] == 0:
temp = [nums[i], nums[j], nums[k]]
hsh = tuple(sorted(temp))
if hsh not in seen:
res.append(temp)
seen.add(hsh)
return res
(2)原数组排序+双指针
解题思路:
1. 先将数组排序。
2. 排序后,可以按照TwoSum的思路来解题。怎么解呢?可以将num[i]的相反数即-num[i]作为target,然后从i+1到len(num)-1的数组元素中寻找两个数使它们的和为-num[i]就可以了。下标i的范围是从0到len(num)-3。
3. 这个过程要注意去重。
4. 时间复杂度为O(N^2)。
已经AC的代码:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums) - 2):
if i == 0 or nums[i] > nums[i - 1]:
left = i + 1
right = len(nums) - 1
while left < right:
if nums[left] + nums[right] == -nums[i]:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]: left += 1
while left < right and nums[right] == nums[right + 1]: right -= 1
elif nums[left] + nums[right] < -nums[i]:
left += 1
else:
right -= 1
return res