Leetcode 2032. Two Out of Three
You are given three integer arrays nums1
, nums2
, and nums3
, and you need to return a list of integers that appear in at least two out of the three arrays.
-100
to 100
.100
elements.nums1
, nums2
, and nums3
into sets to remove duplicates within each array.O(n)
time, where n
is the number of elements in the array.O(m)
, where m
is the total number of distinct elements across all three sets.O(n + m)
.#include <vector>
#include <unordered_set>
#include <unordered_map>
std::vector<int> twoOutOfThree(std::vector<int>& nums1, std::vector<int>& nums2, std::vector<int>& nums3) {
// Convert input arrays to sets to remove duplicates within each array.
std::unordered_set<int> set1(nums1.begin(), nums1.end());
std::unordered_set<int> set2(nums2.begin(), nums2.end());
std::unordered_set<int> set3(nums3.begin(), nums3.end());
// Dictionary to count occurrences across the three sets
std::unordered_map<int, int> count_map;
// Update count_map for each number in the sets
for (int num : set1) {
count_map[num]++;
}
for (int num : set2) {
count_map[num]++;
}
for (int num : set3) {
count_map[num]++;
}
// Result vector
std::vector<int> result;
// Collect numbers that appear in at least two of the three sets
for (const auto& pair : count_map) {
if (pair.second >= 2) {
result.push_back(pair.first);
}
}
return result;
}
In this code:
unordered_map
to count how many sets each number appears in.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?