- Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
返回兩個(gè)數(shù)組的公共元素撒踪,要是相同的有多個(gè)就返回多個(gè)。用一個(gè)哈希表統(tǒng)計(jì)第一個(gè)數(shù)組的每個(gè)數(shù)的個(gè)數(shù)命满,遍歷第二個(gè)數(shù)組链蕊,哈希表里頭有就保存到結(jié)果肥荔,并把哈希表里的這個(gè)數(shù)的個(gè)數(shù)減1。
代碼如下:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> m;
vector<int> res;
for(int i = 0; i < nums1.size(); i++)
{
m[nums1[i]]++;
}
for(int i = 0; i < nums2.size(); i++)
{
m[nums2[i]]--;
if(m[nums2[i]] >= 0)
res.push_back(nums2[i]);
}
return res;
}
};
- Intersection of Two Arrays
和上邊的區(qū)別是重復(fù)的元素只輸出一次。
就在遍歷第二個(gè)數(shù)組的時(shí)候因痛,輸出這個(gè)之后把哈希表里這個(gè)
數(shù)的值置為0就行了。
代碼如下:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> m;
vector<int> res;
for(int i = 0; i < nums1.size(); i++)
{
m[nums1[i]]++;
}
for(int i = 0; i < nums2.size(); i++)
{
m[nums2[i]]--;
if(m[nums2[i]] >= 0)
{
res.push_back(nums2[i]);
m[nums2[i]] = 0;
}
}
return res;
}
};