数组的交集——倒排索引查询,因为不重复,还是可以采用计数的思路做,外部排序,二路归并的做法也不错

793. 多个数组的交集

中文
English

给出多个数组,求它们的交集。输出他们交集的大小。

样例

样例 1:

	输入:  [[1,2,3],[3,4,5],[3,9,10]]
	输出:  1
	
	解释:
	只有3出现在三个数组中。

样例 2:

	输入: [[1,2,3,4],[1,2,5,6,7][9,10,1,5,2,3]]
	输出:  2
	
	解释:
	交集是[1,2].

注意事项

  • 输入的所有数组元素总数不超过500000
  • 题目数据每个数组里的元素没有重复
import heapq


class Solution:
    """
    @param arrs: the arrays
    @return: the number of the intersection of the arrays
    """
    def intersectionOfArrays(self, arrs):
        # write your code here
        q = []
        
        for i, arr in enumerate(arrs):
            if arr:
                arr.sort()
                heapq.heappush(q, (arrs[i][0], i, 0))
        
        ans = 0
        prev = float('inf')
        cnt = 1
        while q:
            val, i, j = heapq.heappop(q)
            
            if val == prev:
                cnt += 1
                if cnt == len(arrs):
                    ans += 1 
            else:
                prev = val
                cnt = 1
                    
            if j+1 < len(arrs[i]):
                heapq.heappush(q, (arrs[i][j+1], i, j+1))
        
        return ans

 此外,还可以使用 二路归并的做法:

import heapq


class Solution:
    """
    @param arrs: the arrays
    @return: the number of the intersection of the arrays
    """
    def intersectionOfArrays(self, arrs):
        # write your code here
        def intersect2(arr1, arr2):
            return list(set(arr1) & set(arr2))
        
        def intersect(arr, l, r):
            if l == r:
                return arr[l]
            
            if l > r:
                return []
                
            mid = (l+r) >> 1
            arr1 = intersect(arr, l, mid)
            arr2 = intersect(arr, mid+1, r)
            return intersect2(arr1, arr2)
        
        return len(intersect(arrs, 0, len(arrs)-1))

 

 

posted @ 2021-01-23 00:26  bonelee  阅读(130)  评论(0编辑  收藏  举报