1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| package com.code.note.test;
import com.code.note.tree.BinaryHeap;
public class Solution2 {
public void buildBigHeap(int[] arr, int parent, int len) { int child = parent * 2 + 1; while (child < len) { if (child + 1 < len && arr[child] < arr[child + 1]) { child++; }
if (arr[child] <= arr[parent]) { break; }
swap(arr, child, parent);
parent = child; child = 2 * child + 1; } }
public void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; }
public void print(int[] arr) { BinaryHeap b = new BinaryHeap(); b.insertLevelOrder(arr); b.print(); }
public int findKthLargest(int[] arr, int k) {
for (int i = arr.length / 2; i >= 0; i--) { buildBigHeap(arr, i, arr.length); }
print(arr);
for (int i = arr.length - 1; i > 0; i--) { swap(arr, 0, i); buildBigHeap(arr, 0, i); } return arr[arr.length - k]; }
public static void main(String[] args) {
Solution2 s = new Solution2();
int[] arr = new int[]{2, 1,4,123};
s.print(arr);
int a = s.findKthLargest(arr, 2);
System.out.println(a); } }
|