解法:两处去重+二分法
python
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
visited_numi = [] # 第一处去重
for i in range(len(nums) - 2):
if nums[i] not in visited_numi:
visited_numi.append(nums[i])
sortnums = nums[i+1: ]
l, r = 0, len(sortnums) - 1
while r > l:
if sortnums[l] + sortnums[r] == - nums[i]:
res.append([nums[i], sortnums[l], sortnums[r]])
while l < r and sortnums[l + 1] == sortnums[l]: l += 1 # 第二处去重
while l < r and sortnums[r - 1] == sortnums[r]: r -= 1
l += 1
r -= 1
elif sortnums[l] + sortnums[r] > - nums[i]: r -= 1
else: l += 1
return res