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

佐手、 提交于 2019-12-21 01:58:55

问题


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 of the two lists.

I can see there is probably a trick here as it requires the nth largest element and the arrays are also of size n, but I can't figure out what it is. I was thinking that I could adapt counting sort, would that work?


回答1:


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.




回答2:


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




回答3:


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);  
}  




}  


来源:https://stackoverflow.com/questions/14535905/an-algorithm-to-find-the-nth-largest-number-in-two-arrays-of-size-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!