classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: if len(nums) < 3:return[] nums = sorted(nums) result = [] for i in range(len(nums)-2): if(nums[i]>0): return result if i > 0and nums[i-1] == nums[i]: continue left, right = i+1, len(nums)-1 while left < right: if nums[i] + nums[left] + nums[right] == 0: result.append([nums[i],nums[left],nums[right]]) while(left<right and nums[left]==nums[left+1]): left += 1 while(left<right and nums[right]==nums[right-1]): right -= 1 left += 1 right -= 1 elif nums[i] + nums[left] + nums[right] < 0: left += 1 else: right -= 1 return result
classSolution: defthreeSumSmaller(self, nums: List[int], target: int) -> int: if len(nums) < 3: # 处理边界条件 return0 nums.sort() ans = 0 for i in range(len(nums) - 2): # 注意i,j,k三个指针不能重合 left = i + 1 right = len(nums) - 1 while left < right: # 如果left和right之和小于target-nums[i],left右移 if nums[i] + nums[left] + nums[right] < target: ans += right - left left += 1 # 如果left和right之和大于target-nums[i],right左移 else: right -= 1 return ans