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.
Values lie in \([1,100]\) and each array has length \(\le 100\). Deduplicate, then test how many of the three sets contain each \(i \in [1,100]\). Keep those present at least twice.
No bit tricks are required under these bounds.
We can first put each element of the arrays into an array, then enumerate each number \(i\) from \(1\) to \(100\), and check whether \(i\) appears in at least two arrays. If so, add \(i\) to the answer array.
The time complexity is \(O(n_1 + n_2 + n_3)\), and the space complexity is \(O(n_1 + n_2 + n_3)\). Here, \(n_1, n_2, n_3\) are the lengths of the arrays nums1, nums2, and nums3, respectively.
Solution 1 hard-codes \(1..100\). A bitmask instead records which arrays contain \(x\) (bit \(i\) for array \(i\)).
\(v\&(v-1)\ne 0\) iff at least two bits are set. One pass, independent of the value range.
We can use a hash table mask to record which arrays each number appears in. For each array, we add its elements to the hash table and set the corresponding bit to 1. For example, if it is the first array, set the corresponding bit to 1; if it is the second array, set it to 2; if it is the third array, set it to 4.
Finally, we iterate through each number in the hash table and check if its corresponding value has at least two bits set to 1 in binary. If so, add that number to the answer array.
The time complexity is \(O(n_1 + n_2 + n_3)\), and the space complexity is \(O(n_1 + n_2 + n_3)\), where \(n_1, n_2, n_3\) are the lengths of the arrays nums1, nums2, and nums3, respectively.