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

前端 未结 3 1799
我在风中等你
我在风中等你 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:20

    Evgeny Kluev gives a better answer - mine was O(n log n) since i didn't think about them as being sorted.

    what i can add is give you a link to a very nice video explaining binary search, courtesy of MIT:

    https://www.youtube.com/watch?v=UNHQ7CRsEtU

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-09 06:28
    public static void main(String[] args) {  
    
    
    int[] fred = { 60, 5, 7, 3, 20, 3, 44 };  
    
    int[] tmp = new int[fred.length];  
    go(fred, 1, tmp, 3);  
    }  
    
    public static void go(int[] fred, int cnt, int[] tmp, int whatPosition) {  
    int max = 0;  
    int currentPosition = 0;  
    for (int i = 0; i < fred.length; i++) {  
    if (i == 0)  
    max = fred[i];  
    else {  
    if (fred[i] > max) {  
    max = fred[i];  
    currentPosition = i;  
    }  
    }  
    }  
    System.arraycopy(fred, 0, tmp, 0, fred.length);  
    tmp[currentPosition] = 0;  
    cnt++;  
    if(cnt != whatPosition)  
    go(tmp, cnt, tmp, whatPosition);  
    else{  
    for (int i = 0; i < tmp.length; i++) {  
    if (i == 0)  
    max = tmp[i];  
    else {  
    if (tmp[i] > max) {  
    max = tmp[i];  
    }  
    }  
    }  
    System.out.println(max);  
    }  
    
    
    
    
    }  
    
    0 讨论(0)
提交回复
热议问题