-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
40 lines (31 loc) · 968 Bytes
/
Copy pathsolution.java
File metadata and controls
40 lines (31 loc) · 968 Bytes
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
36
37
38
39
40
class Solution {
ArrayList<Integer> intersection(int[] a, int[] b) {
ArrayList<Integer> ans = new ArrayList<>();
int i = 0, j = 0;
int n = a.length, m = b.length;
while (i < n && j < m) {
// If current element in a is smaller
if (a[i] < b[j]) {
i++;
}
// If current element in b is smaller
else if (a[i] > b[j]) {
j++;
}
// If both elements are equal
else {
ans.add(a[i]);
int current = a[i];
// Skip duplicates in array a
while (i < n && a[i] == current) {
i++;
}
// Skip duplicates in array b
while (j < m && b[j] == current) {
j++;
}
}
}
return ans;
}
}