If you need the fastest * answer:
- Sorting one array - time N log N.
- For each element in the second array, search for the first. If you find it, add 1 to the companion array; otherwise add 0 - time N log N using space N.
- For each nonzero account, copy the corresponding record into a temporary array, compacting it so that it is still sorted - time is N.
- For each element in the third array, search for a temporary array; when you find a hit, stop. Time is less than N log N.
Here is the code in Scala that illustrates this:
import java.util.Arrays val a = Array(1,5,2,3,14,1,7) val b = Array(3,9,14,4,2,2,4) val c = Array(1,9,11,6,8,3,1) Arrays.sort(a) val count = new Array[Int](a.length) for (i <- 0 until b.length) { val j =Arrays.binarySearch(a,b(i)) if (j >= 0) count(j) += 1 } var n = 0 for (i <- 0 until count.length) if (count(i)>0) { count(n) = a(i); n+= 1 } for (i <- 0 until c.length) { if (Arrays.binarySearch(count,0,n,c(i))>=0) println(c(i)) }
With a bit more complexity, you can either use the extra space due to the even more destructive action of your original arrays, or you can not touch the original arrays at all due to another N.
Edit: * as comments noted, hash tables are faster for non-perverted inputs. This is the "fastest worst case." The worst case may not be so unlikely if you are not using a really good hashing algorithm that could well eat longer than yours. For example, if you multiply all your values โโby 2 ^ 16, trivial hashing (i.e. just use the bit number as an index) will come up each time in lists shorter than 64k ....
Rex kerr
source share