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个数组整体中最大的TOP K,所有数组都是有序的
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- eg:1,2,4,7,10,11,7,12,6,7,16,18,19 索引是3、9 返回值是7
- 前两天面试3面学长问我的这个问题(想说TEG的3个面试学长都是好和蔼,希望能完成最后一面,各方面原因造成我无比想去...
- 给定一个无序的整型数组arr,找到其中最小的k个数 该题是互联网面试中十分高频的一道题,如果用普通的排序算法,排序...