Find the maximum element which is common in two arrays?

后端 未结 6 914
轻奢々
轻奢々 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:22

    You can but using O(N) space.
    Just go through the first array and place all elements in a HashTable. This is O(N)
    Then go through the second array keeping track of the current maximum and checking if the element is in the HashTable. This is also O(N) . So total runtime is O(N) and O(N) extra space for the HashTable

    Example in Java:

    public static int getMaxCommon(int[] a, int[] b){  
      Set firstArray = new HashSet(Arrays.asList(a));  
      int currentMax = Integer.MIN_VALUE;  
      for(Integer n:b){  
         if(firstArray.contains(n)){  
             if(currentMax < n){  
                  currentMax = n  
             }
         }   
      }   
      return currentMax;  
    }  
    

提交回复
热议问题