-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
33 lines (30 loc) · 1 KB
/
Copy pathsolution.java
File metadata and controls
33 lines (30 loc) · 1 KB
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
class Solution {
public ArrayList<Integer> commonElements(int[] a, int[] b, int[] c) {
ArrayList<Integer> ans = new ArrayList<>();
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length && k < c.length) {
int x = a[i], y = b[j], z = c[k];
// Case 1: all three are equal => common element found
if (x == y && y == z) {
// Avoid duplicates in the answer
if (ans.isEmpty() || ans.get(ans.size() - 1) != x) {
ans.add(x);
}
i++;
j++;
k++;
}
// Case 2: move the pointer(s) having the smallest value
else {
int mn = Math.min(x, Math.min(y, z));
if (x == mn)
i++;
if (y == mn)
j++;
if (z == mn)
k++;
}
}
return ans;
}
}