350 两个数组的交集 II
本文最后更新于:2021年1月15日 下午
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
示例 2:
说明:
- 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
- 我们可以不考虑输出结果的顺序。
\进阶\:**
- 如果给定的数组已经排好序呢?你将如何优化你的算法?
- 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
- 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
Solution
- 利用 map,底层数据结构为 平衡二叉树 。
- 时间复杂度 O(nlogn)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { map<int, int> record; for(int num : nums1) record[num] += 1; vector<int> res; for(int n : nums2){ if(record[n] >0){ res.push_back(n); record[n] -= 1; } } return res; } };
|
- 利用 unordered_map,底层数据结构为 哈希表 。
- 时间复杂度 O(n) ( n = len(nums1)+len(nums2) )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> record; for(int num : nums1) record[num] += 1; vector<int> res; for(int n : nums2){ if(record[n] >0){ res.push_back(n); record[n] -= 1; } } return res; } };
|