找到两个数组中常见的最大元素?

sus*_*hil 13 algorithm

给定两个数组,如何找到两个数组共有的最大元素?

我正在考虑对两个数组进行排序(n log n),然后对另一个数组中的一个排序数组(从较大的数组开始)中的每个元素执行二进制搜索,直到找到匹配为止.

例如:

a = [1,2,5,4,3]
b = [9,8,3]

Maximum common element in these array is 3
Run Code Online (Sandbox Code Playgroud)

我们能比n log n做得更好吗?

Kev*_*lia 10

使用一些额外的空间,您可以在1个数组中进行散列,然后在另一个数组的每个元素上执行包含,以跟踪返回true的最大值.是O(n).

  • 只是打败了我.当然,如果散列不是唯一的,那么时间复杂度可能会高一些(验证散列匹配是实际匹配需要搜索)...如果散列是唯一的,则会产生O(n)存储成本. (2认同)

Cra*_*lus 7

你可以使用O(N)空间.
只需浏览第一个数组并将所有元素放在一个数组中HashTable.这是O(N)
然后通过第二个数组跟踪当前最大值并检查元素是否在HashTable.这也是O(N).所以总的运行时间O(N)O(N)额外的空间HashTable

Java中的示例:

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