给出多个数组,求它们的交集。输出他们交集的大小。
样例
给出 [[1,2,3],[3,4,5],[3,9,10]]
,返回 1
。
解释:
只有元素3在所有的数组中出现过。交集为[3],大小为1。
给出 [[1,2,3,4],[1,2,5,6,7],[9,10,1,5,2,3]]
,返回2
。
解释:
只有元素1,2均在所有的数组出现过。交集为[1,2],大小为2。
解题思路:
哈希表。其中value记录当前元素出现的次数,将二维数组所有元素存入unoedered_map中,可以看到如下性质:如果当a元素是交集,则a的value值应该等于arr.size(),因为交集在每个vector中都出现,所以出现的次数是数组的个数。
class Solution {
public:
/**
* @param arrs: the arrays
* @return: the number of the intersection of the arrays
*/
int intersectionOfArrays(vector<vector<int>> &arrs)
{
// write your code here
unordered_map<int,int> m;
for(int i=0;i<arrs.size();i++)
{
for(int j=0;j<arrs[i].size();j++)
{
m[arrs[i][j]]++;
}
}
int res;
for(auto p = m.begin();p != m.end();p++)
if(p->second == arrs.size())
res++;
return res;
}
};