Two Out of Three

• Time:O(n)
• Space:O(100) = O(1)

C++

``````class Solution {
public:
vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2,
vector<int>& nums3) {
vector<int> ans;
vector<int> count(101);

for (const auto& nums : {nums1, nums2, nums3})
update(count, nums);

for (int i = 1; i <= 100; ++i)
if (count[i] >= 2)
ans.push_back(i);

return ans;
}

private:
void update(vector<int>& count, const vector<int>& nums) {
for (const int num : unordered_set<int>(begin(nums), end(nums)))
++count[num];
}
};
``````

JAVA

``````class Solution {
public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
List<Integer> ans = new ArrayList<>();
int[] count = new int[101];

for (int[] nums : new int[][] {nums1, nums2, nums3})
update(count, nums);

for (int i = 1; i <= 100; ++i)
if (count[i] >= 2)

return ans;
}

private void update(int[] count, int[] nums) {
for (final int num : Arrays.stream(nums).boxed().collect(Collectors.toSet()))
++count[num];
}
}
``````

Python

``````class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
count = Counter()
for nums in nums1, nums2, nums3:
count.update(set(nums))
return [i for i, c in count.items() if c >= 2]
``````