day21笔记
1.题目描述
2.代码构思(debug)
排序加快慢指针
哈希表
```class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
# nums1.sort()
# nums2.sort()
# length1, length2 = len(nums1), len(nums2)
# intersection = list()
# index1 = index2 = 0
# while index1 < length1 and index2 < length2:
# if nums1[index1] < nums2[index2]:
# index1 += 1
# elif nums1[index1] > nums2[index2]:
# index2 += 1
# else:
# intersection.append(nums1[index1])
# index1 += 1
# index2 += 1
# return intersection
# 哈希表
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
m = collections.Counter()
for num in nums1:
m[num] += 1
intersection = list()
for num in nums2:
if (count := m.get(num, 0)) > 0:
intersection.append(num)
m[num] -= 1
if m[num] == 0:
m.pop(num)
return intersection
![在这里插入图片描述](https://img-blog.csdnimg.cn/1fc0e075df5e48ccb2541f949d5bdc73.png#pic_center)
![在这里插入图片描述](https://img-blog.csdnimg.cn/1d9296f386954db0bfe6a96ea36d2074.png#pic_center)
```python
``` nums1.sort()
nums2.sort()
length1, length2 = len(nums1), len(nums2)
intersection = list()
index1 = index2 = 0
while index1 < length1 and index2 < length2:
num1 = nums1[index1]
num2 = nums2[index2]
if num1 == num2:
# 保证加入元素的唯一性
if not intersection or num1 != intersection[-1]:
intersection.append(num1)
index1 += 1
index2 += 1
elif num1 < num2:
index1 += 1
else:
index2 += 1
return intersection