Find the maximum element which is common in two arrays?

后端 未结 6 916
轻奢々
轻奢々 2021-02-13 15:51

Given two arrays, how to find the maximum element which is common to both the arrays?

I was thinking of sorting both the arrays(n log n) and then perform the binary sear

6条回答
  •  孤独总比滥情好
    2021-02-13 16:07

    Not a perfect, but a simple solution, O(len(array1) + len(array2))

    import sys
    
    
    def find_max_in_common(array1, array2):
        array1 = set(array1)
        array2 = set(array2)
    
        item_lookup = {}
    
        for item in array1:
            item_lookup[item] = True
    
        max_item = -sys.maxsize
    
        intersection = False
    
        for item in array2:
            if not item_lookup.get(item, None):
                continue
            else:
                intersection = True
                if item > max_item:
                    max_item = item
    
        return None if not intersection else max_item
    

提交回复
热议问题