Distinguishing extra element from two arrays?

后端 未结 19 585
爱一瞬间的悲伤
爱一瞬间的悲伤 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:48

    It is impossible to solve this problem without making comparisons. Some modern languages do have set difference and other aggregate operators, but they work by internally making comparisons. If the total array size is odd (not the case here) then it does work to xor the elements together. I suppose the question of whether the ALU's xor op should be considered a comparison is debatable.

    And without specifying a language, you can't refer to a library, so the only possible solution is a comparison-based pseudo-code exposition.

    So here you go:

    a <- first element
    a_count = 1
    b_count = 0
    loop over remaining elements
       if element != a
         b <- element
         ++b_count
       else
         ++a_count
       if found_result
          break loop
    end loop
    
    found_result
       if a_count > 1 and b_count > 0
         the unique one is b
         return true
       if b_count > 1 and a_count > 0 # a_acount actually always > 0
         the unique one is a
         return true
       return false
    
    0 讨论(0)
提交回复
热议问题