Find unique common element from 3 arrays

前端 未结 7 1576
故里飘歌
故里飘歌 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:11

    Use a hashtable mapping objects to frequency counts. Iterate through all three lists, incrementing occurrence counts in the hashtable, until you encounter one with an occurrence count of 3. This is O(n), since no sorting is required. Example in Python:

    def find_duplicates(*lists):
      num_lists = len(lists)
      counts = {}
      for l in lists:
        for i in l:
          counts[i] = counts.get(i, 0) + 1
          if counts[i] == num_lists:
            return i
    

    Or an equivalent, using sets:

    def find_duplicates(*lists):
      intersection = set(lists[0])
      for l in lists[1:]:
        intersection = intersection.intersect(set(l))
      return intersection.pop()
    

提交回复
热议问题