""" two pointers """ classSolution: deffourSum(self, nums:list, target:int): # 0. 排序 # 1. 兩層迴圈,固定前兩個元素 # 2. two pointer 解target - 兩元素相加 nums.sort() res = [] for i inrange(len(nums)): # 剪枝[可略]: 元素>target and 後面元素均>0 if nums[i] > target and nums[i] > 0: break
# 去重 if i > 0and nums[i] == nums[i-1]: continue
for j inrange(i+1, len(nums)): # 剪枝[可略]: 元素相加>target and 後面元素均>0 if nums[i] + nums[j] < target and nums[j] > 0: break
# 去重 if j > i+1and nums[j] == nums[j-1]: continue
# two sum(sub_target) left, right = j+1, len(nums)-1 while left < right: s = nums[i] + nums[j] + nums[left] + nums[right] if target == s: res.append([nums[i], nums[j], nums[left], nums[right]])
# 去重(left) while left < right and nums[left] == nums[left+1]: left += 1 # 去重(right) while left < right and nums[right] == nums[right-1]: right -= 1
# 已加入list left += 1 right -= 1 elif s < target: left += 1 else: right -= 1 return res