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

    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))
    
  • 相关阅读:
    编程随想——从基础开始,顺其自然
    多个SSH私钥配置不当导致Git push 失败的分析及解决方法
    VPS配置记录
    COCI 2010.03.06 T5「PROGRAM」题解
    筛素数
    你的第一个程序--基本输入输出介绍,头文件介绍
    入门指北目录
    尺取法
    HAOI2006 (洛谷P2341)受欢迎的牛 题解
    c++并查集配合STL MAP的实现(洛谷P2814题解)
  • 原文地址:https://www.cnblogs.com/bonelee/p/14316113.html
Copyright © 2011-2022 走看看