Leetcode 350. Intersection of Two Arrays II
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays, and you may return the result in any order.
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
nums1
or nums2
do not have overlaps?
nums1
.nums2
, and for each element, if the element exists in the hash map and its count is greater than zero, add it to the result and decrement its count in the hash map.nums1
takes O(n), where n
is the length of nums1
.nums2
and finding intersections takes O(m), where m
is the length of nums2
.#include <vector>
#include <unordered_map>
std::vector<int> intersect(std::vector<int>& nums1, std::vector<int>& nums2) {
std::unordered_map<int, int> countMap;
for (int num : nums1) {
countMap[num]++;
}
std::vector<int> intersection;
for (int num : nums2) {
if (countMap[num] > 0) {
intersection.push_back(num);
countMap[num]--;
}
}
return intersection;
}
countMap
to store the count of each element in nums1
.nums1
and populate the countMap
.intersection
to store the result.nums2
, for each element, check if it exists in countMap
with a count greater than 0:
intersection
and decrement the count in countMap
.intersection
vector as the result.This solution ensures that we only include elements in the result the number of times they appear in both nums1
and nums2
, and it uses efficient operations with a hash map for fast lookups and updates.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?