The Intersection of Two Arrays II solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Intersection of Two Arrays II
C++, Python and TypeScript solutions for Intersection of Two Arrays II.
Solution files
Python•intersection-of-two-arrays-ii/synced-solution.py
def intersect(nums1, nums2):
from collections import Counter
count = Counter(nums1)
result = []
for num in nums2:
if count[num] > 0:
result.append(num)
count[num] -= 1
return result
C++•intersection-of-two-arrays-ii/synced-solution.cpp
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> count;
vector<int> result;
for (int num : nums1) {
count[num]++;
}
for (int num : nums2) {
if (count[num] > 0) {
result.push_back(num);
count[num]--;
}
}
return result;
}
};
TypeScript•intersection-of-two-arrays-ii/synced-solution.ts
function intersect(nums1: number[], nums2: number[]): number[] {
const count = new Map<number, number>();
for (const num of nums1) {
count.set(num, (count.get(num) || 0) + 1);
}
const result: number[] = [];
for (const num of nums2) {
if (count.has(num) && count.get(num)! > 0) {
result.push(num);
count.set(num, count.get(num)! - 1);
}
}
return result;
}