Skip to content

Commit cd0ecac

Browse files
authored
Update Intersection of Three Sorted Arrays.java
1 parent 399f496 commit cd0ecac

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed
Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
11
class Solution {
22
public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
3-
int[] counter = new int[2001];
4-
updateCounter(counter, arr1);
5-
updateCounter(counter, arr2);
6-
updateCounter(counter, arr3);
7-
List<Integer> ans = new ArrayList<>();
8-
for (int i = 0; i < 2001; i++) {
9-
if (counter[i] == 3) {
10-
ans.add(i);
3+
int idxOne = 0;
4+
int idxTwo = 0;
5+
int idxThree = 0;
6+
List<Integer> result = new ArrayList<>();
7+
while (idxOne < arr1.length && idxTwo < arr2.length && idxThree < arr3.length) {
8+
if (arr1[idxOne] == arr2[idxTwo] && arr2[idxTwo] == arr3[idxThree]) {
9+
result.add(arr1[idxOne]);
10+
idxOne++;
11+
idxTwo++;
12+
idxThree++;
13+
} else {
14+
int max = Math.max(arr1[idxOne], Math.max(arr2[idxTwo], arr3[idxThree]));
15+
if (arr1[idxOne] < max) {
16+
idxOne++;
17+
}
18+
if (arr2[idxTwo] < max) {
19+
idxTwo++;
20+
}
21+
if (arr3[idxThree] < max) {
22+
idxThree++;
23+
}
1124
}
1225
}
13-
return ans;
14-
}
15-
16-
private void updateCounter(int[] counter, int[] arr) {
17-
for (int num : arr) {
18-
counter[num]++;
19-
}
26+
return result;
2027
}
2128
}

0 commit comments

Comments
 (0)