350. Intersection of Two Arrays II
❀ Origin
Problem
Given two arrays, write a function to compute their intersection.
Example
1 | Input: nums1 = [1,2,2,1], nums2 = [2,2] |
Example 2
1 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] |
Note
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
- What if elements of nums2 are stored on disk,
and the memory is limited such that you cannot load all elements into the memory at once?
❀ 翻譯
問題
給定兩個陣列,
寫出一個 function 去計算出他們的交叉點。
筆記
- 回傳結果的每一個元素都應該出現在兩個陣列中數次以上。
- 回傳結果可以允許任意的排序方式。
進一步思考
- 如果給定的陣列已經排序過了怎麼辦? 你會如何因此去優化演算法?
- 如果 nums1 的尺寸與 nums2 的尺寸相比較小怎麼辦? 哪種算法更好?
- 如果 nums2 的元素都儲存在磁碟上,
導致你無法一次將所有元素加載在內存記憶體的時候,該怎麼辦?
❀ Solution
Golang
1 | /** |
Golang
1 | /** |