题目:
349. 两个数组的交集(Easy)
代码
1.哈希表 + set清重 + 两次遍历:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
dict = {}
ret = []
for i in set(nums1) :
if i not in dict:
dict[i] = 0
for j in set(nums2):
if j in dict :
ret.append(j)
return ret
2.本身已经用了Set的基础上,直接用集合交集:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1)&set(nums2))
# & 交集
# ^ 亦或
# | 非
题目:
350. 两个数组的交集 II(Easy)
代码:
# HASH 遍历
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
dict = {}
ret = []
for i in nums1 :
if i not in dict:
dict[i] = 1
else:
dict[i]+=1
for i in nums2 :
if i in dict and dict[i]!= 0:
ret.append(i)
dict[i]-=1
return ret
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
# 参考题解的双指针算法;
# index1 指向nums1
# index2 指向nums2
# 1.先排序:
nums1.sort()
nums2.sort()
# 2.获取指针最长移动距离:
length1 , length2 = len(nums1),len(nums2)
# 3.用于返回结果的空列表:
ret = []
# 4.初始化双指针:
index1 = index2 = 0
# 5.开始循环,循环终止条件,双方的指针都指向数组末尾:
while index1 < length1 and index2 < length2:
# 6.从初始位开始比较,谁小谁指针加一步,不小就向返回list加数,两个人都加一步;
if nums1[index1] < nums2[index2]:
index1+=1
elif nums1[index1] > nums2[index2]:
index2+=1
else:
ret.append(nums1[index1])
index1+=1
index2+=1
return ret