Find the top k sums of two sorted arrays

前端 未结 4 2068
独厮守ぢ
独厮守ぢ 2021-02-06 01:33

You are given two sorted arrays, of sizes n and m respectively. Your task (should you choose to accept it), is to output the largest k sums of the form a[i]+b[j].

4条回答
  •  佛祖请我去吃肉
    2021-02-06 02:09

    private static class FrontierElem implements Comparable {
        int value;
        int aIdx;
        int bIdx;
    
        public FrontierElem(int value, int aIdx, int bIdx) {
            this.value = value;
            this.aIdx = aIdx;
            this.bIdx = bIdx;
        }
    
        @Override
        public int compareTo(FrontierElem o) {
            return o.value - value;
        }
    
    }
    
    public static void findMaxSum( int [] a, int [] b, int k ) {
        Integer [] frontierA = new Integer[ a.length ];
        Integer [] frontierB = new Integer[ b.length ];
        PriorityQueue q = new PriorityQueue();
        frontierA[0] = frontierB[0]=0;
        q.add( new FrontierElem( a[0]+b[0], 0, 0));
        while( k > 0 ) {
            FrontierElem f = q.poll();
            System.out.println( f.value+"    "+q.size() );
            k--;
            frontierA[ f.aIdx ] = frontierB[ f.bIdx ] = null;
            int fRight = f.aIdx+1;
            int fDown = f.bIdx+1;
            if( fRight < a.length && frontierA[ fRight ] == null ) {
                q.add( new FrontierElem( a[fRight]+b[f.bIdx], fRight, f.bIdx));
                frontierA[ fRight ] = f.bIdx;
                frontierB[ f.bIdx ] = fRight;
            }
            if( fDown < b.length && frontierB[ fDown ] == null ) {
                q.add( new FrontierElem( a[f.aIdx]+b[fDown], f.aIdx, fDown));
                frontierA[ f.aIdx ] = fDown;
                frontierB[ fDown ] = f.aIdx;
            }
        }
    }
    

    The idea is similar to the other solution, but with the observation that as you add to your result set from the matrix, at every step the next element in our set can only come from where the current set is concave. I called these elements frontier elements and I keep track of their position in two arrays and their values in a priority queue. This helps keep the queue size down, but by how much I've yet to figure out. It seems to be about sqrt( k ) but I'm not entirely sure about that.

    (Of course the frontierA/B arrays could be simple boolean arrays, but this way they fully define my result set, This isn't used anywhere in this example but might be useful otherwise.)

提交回复
热议问题