Find the top k sums of two sorted arrays

Given two arrays sorted in ascending order, we want to find the kth largest sum such that one element is picked from 1st array and the second element is picked from the 2nd array. I am looking for a solution involving either a min heap or a max heap.
That can be easily done in  O(k) . I'll only assume arrays are sorted in descending order, to simplify notation.
The idea is simple. We'll find 1st, 2nd, .., k-th maximum values one by one. But to even consider pair (i, j)  we need to have both  (i-1, j)  and  (i, j-1)  already selected, because they both are greater or equal than  (i, j) .
It's much like if we push all  n*m  pairs into the heap and then remove max  k  times. Only we don't need all  n*m  pairs.
heap.add(pair(0, 0));  // biggest pair

// remove max k-1 times
for (int i = 0; i < k - 1; ++i) {
    // get max and remove it from the heap
    max = heap.popMax();

    // add next candidates
    heap.add(pair(max.i + 1, max.j));
    heap.add(pair(max.i, max.j + 1));
}

// get k-th maximum element
max = heap.popMax();
maxVal = a[max.i] + b[max.j];

Some things to consider.
Duplicated pairs can be added to the heap, this can be prevented with hash.
Indexes need to be validated, e.g. that  max.i + 1 < a.length .
_______________________________________________________________________
This can be done in O(klogk) using a max-heap.
1.Start from the first two elements of the sorted arrays.Store their sum and the corresponding index into from the arrays in the heap i.e first element of the heap will contain (A[0]+B[0], 0-->index in array A,0-->index in array B)
2.We need to do Extract_Max operation k times and we need to insert two elements at each step.So there'll be at max 2*k insertions and each step we'll insert two elements based on the element extracted. Suppose for the node extracted...i--->index in array A and j--->index in array B. Then we'll insert A[i + 1][j] and A[i][j + 1] in the heap.
So the complexity will be O(klogk).
sorry we need to insert (A[i] + B[j+1],i,j+1) and (A[i+1]+B[j],i+1,j) instead of A[i][j+1] and A[i+1][j].
여기에 max heap를 실현하는 코드가 있습니다.http://blog.csdn.net/jiyanfeng1/article/details/41404243

좋은 웹페이지 즐겨찾기