Distinguishing extra element from two arrays?

后端 未结 19 648
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 09:45

One of my friend was asked this question in an interview -

  • You have given two integer arrays each of size 10.
  • Both contains 9 equal elements (say 1 t
19条回答
  •  执念已碎
    2020-12-28 10:30

    • You have given two integer arrays each of size 10.
    • Both contains 9 equal elements (say 1 to 9)
    • Only one element is different.

    Depending on the constraints, you can solve this very quickly in linear time. If you hold an int[10], then you can assume that an element at index 1 corresponds to the number 1; the element itself holds a count of both arrays. The following pseudocode will solve the problem quickly:

    let buckets = new int[10] // init all buckets to zero
    for num in arr1 do buckets[num]++ // add numbers from the first array
    for num in arr2 do buckets[num]++ // add from the second array
    for i in 1 to 9 do                // find odd man out
        if buckets[i] <= 1 then return i
    

    This is essentially a bounded hashtable. This only works if our given list of elements is constrained between 1 and 9.

    Technically, you don't even need to keep a running count of each element. You could, in principle, simply loop through arr1, then iterate through arr2 until you run across an element which was not hashed from the first array.

提交回复
热议问题