Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0Find 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]
]
本题应该是leetCode官网在近期添加了一个测试个例,网上好多的解决方法都是TLE。本人刚好找到一位博主分享,参考地址已在最后贴出。
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
length, res = len(nums), []
nums.sort()
# length-2 的原因是3Sum是3个数相加, 下方变量left和right为最后两个
# 数,所以没有必要令 i 循环最后两位数。
for i in range(length - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i + 1, length - 1
while left < right:
result = nums[i] + nums[left] + nums[right]
if result == 0:
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 result < 0:
left += 1
else:
right -= 1
return res
参考:https://blog.csdn.net/fuxuemingzhu/article/details/83115850