classSolution: defisHappy(self, n: int) -> bool: defgetnum(n): res = 0 while n: n,r = divmod(n,10) res+=r**2 return res record = set() whileTrue: n = getnum(n) if n == 1: returnTrue if n in record: returnFalse else: record.add(n)
1、两数之和
1 2 3 4 5 6 7
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: myhash = {} for index,num inenumerate(nums): if target-num in myhash: return [index, myhash[target-num]] myhash[num] = index
15、三数之和
方法1:使用哈希表
将三数之和问题转换为两数之和。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for i inrange(len(nums)): myhash = {} # target = -nums[i] for j inrange(i+1,len(nums)): if -nums[i]-nums[j] in myhash: tmp = [nums[i],nums[j],myhash[-nums[i]-nums[j]]] if tmp notin res: res.append(tmp) myhash[nums[j]] = nums[j] return res