题目
给定一个数组,找出3个元素a,b,c使得它们的和为0。找出所有符合该条件的三元组。
Python题解
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
for i in range(len(nums) - 2):
if i == 0 or nums[i] != nums[i - 1]:
sum2 = 0 - nums[i]
low, high = i + 1, len(nums) - 1
while low < high:
sum_tmp = nums[low] + nums[high]
if sum_tmp == sum2:
res.append([nums[i], nums[low], nums[high]])
low += 1
while low < len(nums) and nums[low] == nums[low - 1]:
low += 1
high -= 1
while high >= 0 and nums[high] == nums[high + 1]:
high -= 1
elif sum_tmp < sum2:
low += 1
else:
high -= 1
return res