mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0349.两个数组的交集.md
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user