Find the unique mapping between elements of two same size arrays

后端 未结 3 1358
南旧
南旧 2021-02-05 20:21

I was recently asked this question in an interview:

There are two arrays of size \'n\' each. One array has nuts, the other one has bolts. Each nut fits exactly one bolt

3条回答
  •  无人及你
    2021-02-05 20:52

    Take one nut N0 and compare it against all bolts. With the resulting information, we can split the bolts array into [bolts smaller than B0] + B0 + [bolts larger than B0]. There is always a unique B0 that fits N0 based on the statement of the question.

    Then take the next nut N1 and compare it against B0. If the result is "tight", we search the smaller half as we did above with N0. Otherwise, we do the same but with the larger half. Doing this will further split one of the two halves into 2.

    Continue doing this until you've worked through all nuts. This is equivalent to quicksort. Average case is O(N logN), but there's the obvious worst case complexity of O(N^2) when the list is "sorted" already.

提交回复
热议问题