Array:打印N个数组整体中最大的TOP K,所有数组都是有序的

class HeapNode {
    public int value;
    public int arrNum;
    public int index;

    public HeapNode(int value, int arrNum, int index) {
        this.value = value;
        this.arrNum = arrNum;
        this.index = index;
    }
}
public static void printTopK(int[][] matrix,int topK) {
        int heapSize = matrix.length;
        HeapNode[] heapNodes = new HeapNode[heapSize];
        for (int i = 0; i < heapSize; i++) {
            heapNodes[i] = new HeapNode(matrix[i][matrix[i].length-1], i, matrix[i].length-1);
            insertHeap(heapNodes, i);
        }
        for (int i = 0; i < topK; i++) {
            if (heapSize==0) {
                break;
            }
            System.out.println(heapNodes[0].value);
            if (heapNodes[0].index!=0) {
                heapNodes[0] = new HeapNode(matrix[heapNodes[0].arrNum][heapNodes[0].index-1], heapNodes[0].arrNum, heapNodes[0].index-1);
            } else {
                swap(heapNodes, 0, --heapSize);
            }
            heapify(heapNodes, 0, heapSize);
        }
    }
    public static void swap(HeapNode[] heap,int index1,int index2) {
        HeapNode tempHeapNode = heap[index1];
        heap[index1] = heap[index2];
        heap[index2] = tempHeapNode;
    }
    public static void insertHeap(HeapNode[] heap,int index) {
        while (index != 0) {
            if (heap[(index-1)/2].value

你可能感兴趣的:(Array:打印N个数组整体中最大的TOP K,所有数组都是有序的)