Find the maximum element which is common in two arrays?

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

    While it depends on the time complexities of the various operations in specific languages, how about creating sets from the arrays and finding the maximum value in the intersection of the two sets? Going by the time complexities for operations in Python, it'd be, on average, O(n) for the set assignments, O(n) for the intersections, and O(n) for finding the max value. So average case would be O(n).

    However! Worst-case would be O(len(a) * len(b)) -> O(n^2), because of the worst-case time complexity of set intersections.

    More info here, if you're interested: http://wiki.python.org/moin/TimeComplexity

提交回复
热议问题