diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 0da0e30c..c2f6ef46 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -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 - - for num in nums2: - if num in val_dict.keys() and val_dict[num] == 1: - ans.append(num) - val_dict[num] = 0 + table[num] = table.get(num, 0) + 1 - 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]: 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