What is the best way to find all equal elements in 2 sorted arrays?
how can I make it done by O(n) ?
What is the best way to find all equal elements in 2 sorted arrays?
how can I make it done by O(n) ?
Since they are both sorted you could walk down them both until you hit the end of either. Assuming integers it would look something like this (Java example). You didn't really define how to handle duplicates so I'm assuming you'd want to see them if they were both arrays many times.
public class TwoArraysWalkIntoABar {
public static void main(String[] args) {
int[] a = { 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 5, 6, 7, 8, 9 };
int[] b = { 2, 4, 4, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int ax = 0, bx = 0;
while (true) {
if (ax >= a.length || bx >= b.length) {
break;
} else if (a[ax] == b[bx]) {
System.out.println("Match: " + a[ax]);
ax++;
bx++;
} else if (a[ax] < b[bx]) {
ax++;
} else if (a[ax] > b[bx]) {
bx++;
}
}
}
}
Results in:
Match: 2
Match: 4
Match: 4
Match: 4
Match: 6
Match: 8