forked from mirandaio/codingbat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommonTwo.java
More file actions
37 lines (34 loc) · 1.03 KB
/
commonTwo.java
File metadata and controls
37 lines (34 loc) · 1.03 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
34
35
36
37
/* Start with two arrays of strings, a and b, each in alphabetical order,
* possibly with duplicates. Return the count of the number of strings which
* appear in both arrays. The best "linear" solution makes a single pass over
* both arrays, taking advantage of the fact that they are in alphabetical
* order.
*/
public int commonTwo(String[] a, String[] b) {
int count = 0;
int aIndex = 0;
int bIndex = 0;
if(a[0].equals(b[0])) {
count++;
aIndex++;
bIndex++;
} else if(a[0].compareTo(b[0]) < 0) {
aIndex++;
} else {
bIndex++;
}
while(aIndex < a.length && bIndex < b.length) {
if(aIndex > 0 && a[aIndex-1].equals(a[aIndex])) {
aIndex++;
} else if(a[aIndex].equals(b[bIndex])) {
count++;
aIndex++;
bIndex++;
} else if(a[aIndex].compareTo(b[bIndex]) < 0) {
aIndex++;
} else {
bIndex++;
}
}
return count;
}