- 两个数组的交集
题目详解
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans=[]
dict1={}
for num in nums1:
dict1[num]=1
for num in nums2:
if num in dict1.keys() and dict1[num]==1:#注意要先判断键值是否存在
ans.append(num)
dict1[num]=0 #注意要置0,不然ans中会有重复
return ans
202. 快乐数
def isHappy(self, n: int) -> bool:
def get_next(n):
total_sum = 0
while n > 0:
n, digit = divmod(n, 10) #记住这个函数,可以求余和商
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
题目详解
本题重点:
为什么想到用哈希表
哈希表的Key和value分别是什么
Key是存值,value 存id
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dictnum = defaultdict(int)
for i,num in enumerate(nums):
need = target-num
if need in dictnum.keys():
return (i,dictnum[need])
if num not in dictnum.keys():
dictnum[num]=i
return ()