mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0349.两个数组的交集.md
This commit is contained in:
@ -160,22 +160,29 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python3:
|
Python3:
|
||||||
|
(版本一) 使用字典和集合
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
||||||
val_dict = {}
|
# 使用哈希表存储一个数组中的所有元素
|
||||||
ans = []
|
table = {}
|
||||||
for num in nums1:
|
for num in nums1:
|
||||||
val_dict[num] = 1
|
table[num] = table.get(num, 0) + 1
|
||||||
|
|
||||||
for num in nums2:
|
|
||||||
if num in val_dict.keys() and val_dict[num] == 1:
|
|
||||||
ans.append(num)
|
|
||||||
val_dict[num] = 0
|
|
||||||
|
|
||||||
return ans
|
# 使用集合存储结果
|
||||||
|
res = set()
|
||||||
|
for num in nums2:
|
||||||
|
if num in table:
|
||||||
|
res.add(num)
|
||||||
|
del table[num]
|
||||||
|
|
||||||
|
return list(res)
|
||||||
|
```
|
||||||
|
(版本二) 使用数组
|
||||||
|
|
||||||
|
```python
|
||||||
|
|
||||||
class Solution: # 使用数组方法
|
class Solution:
|
||||||
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
||||||
count1 = [0]*1001
|
count1 = [0]*1001
|
||||||
count2 = [0]*1001
|
count2 = [0]*1001
|
||||||
@ -190,7 +197,14 @@ class Solution: # 使用数组方法
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
```
|
```
|
||||||
|
(版本三) 使用集合
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
||||||
|
return list(set(nums1) & set(nums2))
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
```go
|
```go
|
||||||
|
Reference in New Issue
Block a user