Distinguishing extra element from two arrays?

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

    Put each element of the first array into a hash. For each item in the second array, if it's already in the hash, remove it, else add it. At the end you have a hash with two keys, which are your unique elements.

    Simple verison in Ruby

    def unique(a,b)
      h={}
      a.each do |ax|
        h[ax]=true
      end
      b.each do |bx|
        if h[bx]
          h.delete(bx)
        else
          h[bx]=true
        end
      end
      h.keys
    end
    

    With a little more Ruby personality, but still in the universe where we can't simply do (a | b) - (a & b) or a.to_set ^ b.to_set:

    def unique(a,b)
      h = {}
      a.each do |ax|
        h[ax] = true
      end
      b.each do |bx|
        h.delete(bx) or h[bx] = true
      end
      h.keys
    end
    

提交回复
热议问题