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<heap[index].value) {
swap(heap, (index-1)/2, index);
} else {
break;
}
}
}
public static void heapify(HeapNode[] heapNodes,int index,int heapSize) {
int largest = index;
int left = index*2+1;
int right = index*2+2;
while (left<heapSize) {
if (heapNodes[index].value<heapNodes[left].value) {
largest = left;
}
if (right<heapSize&& heapNodes[index].value<heapNodes[right].value) {
largest = right;
}
if (largest!=index) {
swap(heapNodes, largest, index);
} else {
break;
}
index = largest;
left = index*2+1;
right = index*2+2;
}
}
Array:打印N個(gè)數(shù)組整體中最大的TOP K,所有數(shù)組都是有序的
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- eg:1,2,4,7,10,11,7,12,6,7,16,18,19 索引是3、9 返回值是7
- 前兩天面試3面學(xué)長問我的這個(gè)問題(想說TEG的3個(gè)面試學(xué)長都是好和藹,希望能完成最后一面,各方面原因造成我無比想去...
- 給定一個(gè)無序的整型數(shù)組arr,找到其中最小的k個(gè)數(shù) 該題是互聯(lián)網(wǎng)面試中十分高頻的一道題,如果用普通的排序算法,排序...
- 比特幣有爭議的屬性之一就是它的固定的供應(yīng)量。為什么總數(shù)的上限是2100萬個(gè)? 首先,我承認(rèn)我的高數(shù)實(shí)在不行,叫我從...