An algorithm to find the nth largest number in two arrays of size n

前端 未结 3 1798
我在风中等你
我在风中等你 2021-02-09 05:56

I have this question:

Given two sorted lists (stored in arrays) of size n, find an O(log n) algorithm that computes the nth largest element in the union

3条回答
  •  醉话见心
    2021-02-09 06:26

    Compare A[n/2] and B[n/2]. If equal, any of them is our result. Other stopping condition for this algorithm is when both arrays are of size 1 (either initially or after several recursion steps). In this case we just choose the largest of A[n/2] and B[n/2].

    If A[n/2] < B[n/2], repeat this procedure recursively for second half of A[] and first half of B[].

    If A[n/2] > B[n/2], repeat this procedure recursively for second half of B[] and first half of A[].

    Since on each step the problem size is (in worst case) halved, we'll get O(log n) algorithm.


    Always dividing array size by two to get the index works properly only if n is a power of two. More correct way of choosing indexes (for arbitrary n) would be using the same strategy for one array but choosing complementing index: j=n-i for other one.

提交回复
热议问题