Given three integer arrays nums1
, nums2
, and nums3
, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.
Example 1:
Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] Output: [3,2] Explanation: The values that are present in at least two arrays are: - 3, in all three arrays. - 2, in nums1 and nums2.
Example 2:
Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] Output: [2,3,1] Explanation: The values that are present in at least two arrays are: - 2, in nums2 and nums3. - 3, in nums1 and nums2. - 1, in nums1 and nums3.
Example 3:
Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5] Output: [] Explanation: No value is present in at least two arrays.
Constraints:
1 <= nums1.length, nums2.length, nums3.length <= 100
1 <= nums1[i], nums2[j], nums3[k] <= 100
// OJ: https://leetcode.com/problems/two-out-of-three/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(R) where `R` is the range of the numbers in arrays.
class Solution {
public:
vector<int> twoOutOfThree(vector<int>& A, vector<int>& B, vector<int>& C) {
unordered_set<int> a(begin(A), end(A)), b(begin(B), end(B)), c(begin(C), end(C));
unordered_map<int, int> cnt;
for (int n : a) cnt[n]++;
for (int n : b) cnt[n]++;
for (int n : c) cnt[n]++;
vector<int> ans;
for (auto [n, c] : cnt) {
if (c >= 2) ans.push_back(n);
}
return ans;
}
};
Or
// OJ: https://leetcode.com/problems/two-out-of-three/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(R) where `R` is the range of the numbers in arrays.
class Solution {
public:
vector<int> twoOutOfThree(vector<int>& A, vector<int>& B, vector<int>& C) {
bool seen[3][101] = {};
for (int n : A) seen[0][n] = true;
for (int n : B) seen[1][n] = true;
for (int n : C) seen[2][n] = true;
vector<int> ans;
for (int i = 1; i <= 100; ++i) {
if (seen[0][i] + seen[1][i] + seen[2][i] >= 2) ans.push_back(i);
}
return ans;
}
};