classSolution: defisHappy(self, n: int) -> bool: #计算每次的平方和 defcalculate_happy(num) : s = 0 while num : s += (num % 10) * (num % 10) num //= 10 return s
#哈希记录平方和 record = set() whileTrue : n = calculate_happy(n) if n == 1: returnTrue #如果出现重复的平方和,说明这个数不是快乐数 if n in record : returnFalse else : record.add(n) returnTrue
classSolution: defthreeSum(self, nums): ans = [] nums.sort()
for i inrange(len(nums)) : #如果第一个数大于0,则找不到解 if nums[i] > 0 : break
left = i + 1 #右指针指向数组的末尾 right = len(nums) - 1
#对第一个元素去重 if i > 0and nums[i] == nums[i - 1] : continue while left < right : total = nums[i] + nums[left] + nums[right]
#如果和大于0,则要减小和即让右指针左移 if total > 0 : right -= 1 #如果和小于0,则要增大和即让左指针右移 elif total < 0 : left += 1 else : #找到一组解 ans.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 return ans
classSolution: deffourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() ans = [] for i inrange(len(nums)) : if i > 0and nums[i] == nums[i - 1] : continue
for j inrange(i + 1, len(nums)) : if j > i + 1and nums[j] == nums[j - 1] : continue
left = j + 1 right = len(nums) - 1
while left < right : total = nums[i] + nums[j] + nums[left] + nums[right] if total > target : right -= 1 elif total < target : left += 1 else : ans.append([nums[i], nums[j], 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 return ans