class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""# 思路:转为两数之和# for循环遍历先固定一个数字a,寻找另外两个数字之和=-a(双指针)# 难点:去重{1. 排序; 2.加规则约束}nums = sorted(nums)res = []for i in range(len(nums)):if nums[i] > 0: # 剪枝,nums[i]若为正数,后边的也都是正数,没有匹配的了。return resif i > 0 and nums[i] == nums[i-1]: # 写 nums[i] == nums[i+1],会越界continuetar = 0 - nums[i]left, right = i + 1, len(nums) - 1while left < right:summ = nums[left] + nums[right]if summ == tar:res.append([nums[i], nums[left], nums[right]])while left < right and nums[left] == nums[left+1]:left += 1while left < right and nums[right] == nums[right-1]:right -= 1left += 1right -= 1elif summ < tar:left += 1else:right -= 1return res