Leetcode 2248. Intersection of Multiple Arrays
Given a 2D integer array nums
where nums[i]
is a list of integers, return a list of integers that are present in each array of nums
sorted in ascending order.
Example:
Input: nums = [[3,1,2,4,5], [1,2,3,4], [3,4,5,6,7]]
Output: [3, 4]
#include <vector>
#include <unordered_map>
#include <algorithm>
std::vector<int> intersectionOfArrays(const std::vector<std::vector<int>>& nums) {
std::unordered_map<int, int> countMap;
int listCount = nums.size();
// Count the occurrence of each integer across all subarrays
for (const auto& sublist : nums) {
for (int num : sublist) {
countMap[num]++;
}
}
std::vector<int> result;
// Collect integers that appear in all subarrays
for (const auto& entry : countMap) {
if (entry.second == listCount) {
result.push_back(entry.first);
}
}
// Sort the result in ascending order
std::sort(result.begin(), result.end());
return result;
}
n
is the number of subarrays and m
is the average length of the subarrays.k
is the number of unique integers counted.k
is the number of common integers.This approach ensures a clear and efficient way to find the intersection of numbers present in every array, while also considering the sorting of the resultant intersection.
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?