Topic
打印N 个数组整体最大的Top K
Java code
Package com.lizhouwei.chapter8;/** * @Description: Print n number of groups the largest top K * @Author: Lizhouwei * @CreateDate: 2018/5/9 20:11 * @Modify by: * @ModifyDate: */public class Chapter8_20 {public void printtopk (int[][] matrix, int topK) {int he Apsize = Matrix.length; heapnode[] heap = new Heapnode[heapsize]; for (int i = 0; i < heapsize; i++) {int index = MATRIX[I].LENGTH-1; Heap[i] = new Heapnode (Matrix[i][index], I, index); Heapinsert (heap, i); } System.out.print ("TOP" + TopK + ":"); Heapnode node = null; for (int i = 0; i < TopK; i++) {System.out.print (Heap[0].value + ""); if (Heap[0].index! = 0) {heap[0].value = Matrix[heap[0].arrnum][--heap[0].index]; } else {swap (heap, 0,--heapsize); } heapify (heap, 0, heapsize); }} public void Heapinsert (heapnode[] heap, int index) {int parent = 0; while (Index > 0) {parent = (index-1)/2; if (Heap[parent].value < Heap[index].value) {swap (heap, parent, index); } else {break; }}} public void Heapify (heapnode[] heap, int index, int. heapsize) {int left = 2 * index + 1; int right = 2 * index + 2; int largest = index; while (left < heapsize) {if (Heap[left].value > Heap[index].value) {largest = left; } if (Right < heapsize && Heap[right].value > Heap[largest].value) {Large st = right; } if (largest = = index) {break; } swap (heap, largest, index); index = largest; left = 2 * index + 1; right = 2 * index + 2; }} public void Swap (heapnode[] heap, int a, int b) {Heapnode temp = heap[a]; Heap[a] = heap[b]; HEAP[B] = temp; }}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; }//test public static void main (string[] args) {chapter8_20 chapter = new chapter8_20 (); Int[][] arr = {{219, 405, 538, 845, 971}, {148, 558}, {52, 99, 348, 691}}; CHAPTER.PRINTTOPK (arr, 5); }}
Results
Code interview guide for Programmers eighth chapter array and matrix problems printing n number of groups the largest top K