Find the maximum element which is common in two arrays?

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

    Pseudocode:

    sort list1 in descending order
    sort list2 in descending order
    item *p1 = list1
    item *p2 = list2
    while ((*p1 != *p2) && (haven't hit the end of either list))
      if (*p1 > *p2)
        ++p1;
      else
        ++p2;
    // here, either we have *p1 == *p2, or we hit the end of one of the lists
    if (*p1 == *p2)
      return *p1;
    return NOT_FOUND;
    

提交回复
热议问题