File tree Expand file tree Collapse file tree 1 file changed +63
-2
lines changed Expand file tree Collapse file tree 1 file changed +63
-2
lines changed Original file line number Diff line number Diff line change @@ -207,15 +207,44 @@ class Solution:
207207 return True
208208```
209209
210+ ## 349. 两个数组的交集
211+
212+ [ 原题链接] ( https://leetcode-cn.com/problems/intersection-of-two-arrays/ )
213+
214+ ### 解一:内置函数
215+
216+ ``` python
217+ class Solution :
218+ def intersection (self , nums1 : List[int ], nums2 : List[int ]) -> List[int ]:
219+ return list (set (nums1) & set (nums2))
220+ ```
221+
222+ #### 复杂度
223+
224+ - 时间复杂度:将数组转为 ` set ` 的复杂度为 ` O(n) ` ,转化两个数组时间复杂度 ` O(m) + O(n) `
225+ - 平均情况下:` O(m + n) `
226+ - 最坏情况下:` O(m * n) `
227+ - 空间复杂度:最坏情况 ` O(m + n) ` (数组元素都不同的情况)
228+
229+ ### 解二:排序 + 双指针
230+
231+ 先对二者排序,使用双指针滑动查找。
232+
233+ ### 解三:排序 + 二分查找
234+
235+ 一个数组排序(短数组?),另一数组内的元素使用二分查找。
210236
211237## 350. 两个数组的交集 II
212238
213239[ 原题链接] ( https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ )
214240
215- ### 解法一
241+ ### 解法一:哈希
216242
217243使用 hash 表的方式。
218244
245+ - 遍历较短数组,将数据存储在哈希表中,存储的值为数字出现的次数
246+ - 遍历较长数组,查询数据是否在哈希表出现过
247+
219248空间复杂度 ` O(n) ` ,时间复杂度 ` O(n) ` 。
220249
221250``` python
@@ -243,10 +272,42 @@ class Solution(object):
243272 return res
244273```
245274
246- ### 解法二
275+ #### 复杂度
276+
277+ - 时间复杂度:` O(m + n) `
278+ - 空间复杂度:` O(min(m, n)) ` (不会超过短数组长度)
279+
280+ ### 解法二:排序 + 双指针
247281
248282排序 + 双指针,不需要额外空间。
249283
284+ ``` python
285+ class Solution :
286+ def intersect (self , nums1 : List[int ], nums2 : List[int ]) -> List[int ]:
287+ nums1.sort()
288+ nums2.sort()
289+ i = 0
290+ j = 0
291+ length1 = len (nums1)
292+ length2 = len (nums2)
293+ res = []
294+ while i < length1 and j < length2:
295+ if nums1[i] == nums2[j]:
296+ res.append(nums1[i])
297+ i += 1
298+ j += 1
299+ elif nums1[i] < nums2[j]:
300+ i += 1
301+ else :
302+ j += 1
303+ return res
304+ ```
305+
306+ #### 复杂度
307+
308+ - 事件复杂度:` mO(logm) + nO(logn) `
309+ - 空间复杂度:` O(len(res)) ` (结果答案长度)
310+
250311## 355. 设计推特
251312
252313[ 原题链接] ( https://leetcode-cn.com/problems/design-twitter/ )
You can’t perform that action at this time.
0 commit comments