描述
计算两个数组的交
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出
您在真实的面试中是否遇到过这个题?
是
样例
nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2, 2]
.
挑战
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to num2'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?
我依旧使用了关联容器,这道题的考察可能是排序?
class Solution {
public:
/*
* @param nums1: an integer array
* @param nums2: an integer array
* @return: an integer array
*/
vector<int> intersection(vector<int> nums1, vector<int> nums2) {
// write your code here
map<int,int> hash;
vector<int> m_vec;
for(int i=0;i<nums1.size();i++) hash[nums1[i]]++;
for(int i=0;i<nums2.size();i++)
if(hash[nums2[i]]>=1){
m_vec.push_back(nums2[i]);
--hash[nums2[i]];
}
return m_vec;
}
};