From 3065cf38604dd672ad128a445b98c356604eb24e Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:04:47 -0500 Subject: [PATCH] =?UTF-8?q?Update=200349.=E4=B8=A4=E4=B8=AA=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0349.两个数组的交集.md | 34 ++++++++++++++++++-------- 1 file changed, 24 insertions(+), 10 deletions(-) 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