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
| class Solution { public int findKthLargest(int[] nums, int k) { int[] arrays = new int[k+1]; for(int i = 1 ; i<= k ; i++ ){ arrays[i] = nums[i-1]; } initTree(arrays); for(int i = k ; i< nums.length ; i++){ int min = arrays[1]; if(min < nums[i]){ arrays[1] = nums[i]; heapify(arrays,1, k); } } return arrays[1]; } private void initTree(int[] array){ for(int i = array.length/2; i>= 1;i--){ heapify(array, i, array.length -1); } } private void heapify(int[] array,int i, int n){ while(true){ int minPos = i; if(i*2 <= n && array[i] > array[i*2]){ minPos = i*2; } if(i*2+1 <= n && array[minPos] > array[i*2+1]){minPos = i*2+1;} if(minPos == i)break; swap(array, i, minPos); i = minPos; } } public void swap(int[] nums , int fromIndex , int toIndex){ int tmp = nums[toIndex]; nums[toIndex] = nums[fromIndex]; nums[fromIndex] = tmp; }
|