Find the unique mapping between elements of two same size arrays

后端 未结 3 1365
南旧
南旧 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:39

    The quicksort like algorithm does the job:

    1. Randomly pick a nut n and use it as pivot to partition the set of bolts B into three sets: tight (B1), loose (B2), fits.
    2. Mark the fit bolt as b. Now you use this bolt as pivot to partition the nuts set N\n into two set: tight (N1) or loose (N2).
    3. Now you have three pairs: N1 and B1, n and b, N2 and B2. All of them are of the same size. You can do the same partitioning recursively on (N1,B2) and (N2,B1) and you can get the final answer.

    It is obvious the complexity is O(N log N), the same as quicksort.

提交回复
热议问题