forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwoOutOfThree.java
35 lines (32 loc) · 1.2 KB
/
TwoOutOfThree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// https://leetcode.com/problems/two-out-of-three
// T: O(|nums1| + |nums2| + |nums3|)
// S: O(|nums1| + |nums2| + |nums3|)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TwoOutOfThree {
public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
final Set<Integer> set1 = getElements(nums1);
final Set<Integer> set2 = getElements(nums2);
final Set<Integer> set3 = getElements(nums3);
final Set<Integer> resultElements = new HashSet<>();
for (int element : set1) {
if (set2.contains(element) || set3.contains(element)) {
resultElements.add(element);
}
}
for (int element : set2) {
if (set3.contains(element)) resultElements.add(element);
}
// return resultElements.stream().toList(); // cant be used because LeetCode is still on a previous version of Java
return new ArrayList<>(resultElements);
}
private Set<Integer> getElements(int[] array) {
final Set<Integer> set = new HashSet<>();
for (int element : array) {
set.add(element);
}
return set;
}
}