defselectSort(self,nums): n = len(nums) for i inrange(n-1): min = i # 在剩下的找出比当前的还小的值 for j inrange(i,n): if nums[j] < nums[min]: min = j ifmin != i: nums[i],nums[min] = nums[min],nums[i] return nums
defmergeSortInOrder(self,left:list,right:list): res = []
i = 0 j = 0 while i < len(left) and j < len(right): if left[i] < right[i]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 res += left[i:] res += right[j:] return res
classSolution: defthreeSum(self, nums: list): nums = sorted(nums) n = len(nums) res = []
for i inrange(n-2): if nums[i] > 0 : break # 去重 if i > 0and nums[i] == nums[i-1]: continue
target = -nums[i] # a left = i+1# b right = n - 1# c
while left < right: if nums[left] + nums[right] == target: res.append([nums[i],nums[left],nums[right]])
# left += 1 这里可以不用加 right -= 1# 考虑到边界情况先减1 while left < right and nums[left] == nums[left-1]: left += 1 while left < right and nums[right] == nums[right+1]: right -= 1 elif nums[left] + nums[right] < target: left += 1 else: right -= 1 return res
classSolution: defthreeSumClosest(self, nums: list, target: int) -> int: nums = sorted(nums) n = len(nums) res = [] span = 0# 最大的间隔,间隔是绝对值 print(span) for i inrange(n): # if i > 0 and nums[i-1]== nums[i]:continue left = i+1 right = n-1
while left<right: t = target - nums[i] - nums[left] - nums[right] if span == 0: res.append(target-t) span = abs(t) ifabs(t) <= span: # 说明当前的间隔比现在的间隔小 # print("--") span = abs(t) res.append(target-t) # 向最接近的地方靠近 if nums[i]+nums[left]+nums[right] == target: return target elif nums[i]+nums[left]+nums[right] < target: left += 1 else: right -= 1 # print("--",res) return res[-1]