LeetCode 350. Intersection of Two Arrays II
程序员文章站
2022-07-15 10:46:31
...
题意:求两个数组的相交。要求相同的元素不合并,全部输出。
solution:hash。首先记录第一个数组的元素出现情况count,然后遍历第二个数组,每次先将相应的hash值-1,如果此时hash值仍大于等于0。这么做是因为交集中元素的最大出现次数也不会大于第一个数组的出现次数。
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> hash; // num - count
vector<int> res;
for ( auto n : nums1 ) {
hash[n]++;
}
for ( auto n : nums2 ) {
hash[n]--;
if ( hash[n] > 0 || hash[n] == 0 ) {
res.push_back(n);
}
}
return res;
}
};
submission:
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
【LeetCode】4. Median of Two Sorted Arrays
-
LeetCode 4. 两个排序数组的中位数 Median of Two Sorted Arrays
-
LeetCode算法系列:4、Median of Two Sorted Arrays
-
【leetcode】4. Median of Two Sorted Arrays
-
【leetcode阿里题库】4. Median of Two Sorted Arrays
-
[LC] 349. Intersection of Two Arrays
-
349. Intersection of Two Arrays
-
LeetCode刷题笔记(Intersection of Two Arrays II)