Find unique common element from 3 arrays

前端 未结 7 1601
故里飘歌
故里飘歌 2021-02-03 14:43

Original Problem:
I have 3 boxes each containing 200 coins, given that there is only one person who has made calls from all of the three boxes and thus the

7条回答
  •  一整个雨季
    2021-02-03 15:10

    If you want the fastest* answer:

    • Sort one array--time is N log N.
    • For each element in the second array, search the first. If you find it, add 1 to a companion array; otherwise add 0--time is N log N, using N space.
    • For each non-zero count, copy the corresponding entry into the temporary array, compacting it so it's still sorted--time is N.
    • For each element in the third array, search the temporary array; when you find a hit, stop. Time is less than N log N.

    Here's 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 slightly more complexity, you can either use no extra space at the cost of being even more destructive of your original arrays, or you can avoid touching your original arrays at all at the cost of another N space.


    Edit: * as the comments have pointed out, hash tables are faster for non-perverse inputs. This is "fastest worst case". The worst case may not be so unlikely unless you use a really good hashing algorithm, which may well eat up more time than your sort. For example, if you multiply all your values by 2^16, the trivial hashing (i.e. just use the bitmasked integer as an index) will collide every time on lists shorter than 64k....

提交回复
热议问题