Update 0349.两个数组的交集.md

This commit is contained in:
jianghongcheng
2023-05-05 20:04:47 -05:00
committed by GitHub
parent d590d268d7
commit 3065cf3860

View File

@ -160,22 +160,29 @@ class Solution {
```
Python3
(版本一) 使用字典和集合
```python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
val_dict = {}
ans = []
# 使用哈希表存储一个数组中的所有元素
table = {}
for num in nums1:
val_dict[num] = 1
table[num] = table.get(num, 0) + 1
# 使用集合存储结果
res = set()
for num in nums2:
if num in val_dict.keys() and val_dict[num] == 1:
ans.append(num)
val_dict[num] = 0
if num in table:
res.add(num)
del table[num]
return ans
return list(res)
```
(版本二) 使用数组
class Solution: # 使用数组方法
```python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
count1 = [0]*1001
count2 = [0]*1001
@ -190,7 +197,14 @@ class Solution: # 使用数组方法
return result
```
(版本三) 使用集合
```python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
```
Go
```go