classSolution:deffourSum(self, nums: List[int], target:int)-> List[List[int]]:
num_set =set()
nums.sort()for i inrange(len(nums)-1):for j inrange(i +1,len(nums)):
lo, hi = j +1,len(nums)-1while lo < hi:
four = nums[i]+ nums[j]+ nums[lo]+ nums[hi]if four == target:
num_set.add((nums[i], nums[j], nums[lo], nums[hi]))
lo +=1
hi -=1elif four < target:
lo +=1else:
hi -=1return num_set
加上一句:if i > 0 and nums[i] == nums[i-1]: continue, 加快速度。
classSolution:deffourSum(self, nums: List[int], target:int)-> List[List[int]]:
num_set =set()
nums.sort()for i inrange(len(nums)-1):if i >0and nums[i]== nums[i-1]:continuefor j inrange(i +1,len(nums)):
lo, hi = j +1,len(nums)-1while lo < hi:
four = nums[i]+ nums[j]+ nums[lo]+ nums[hi]if four == target:
num_set.add((nums[i], nums[j], nums[lo], nums[hi]))
lo +=1
hi -=1elif four < target:
lo +=1else:
hi -=1return num_set