核心思想
手写堆
构建一个大顶堆,删除k-1个堆顶元素。
为什么是size / 2 - 1
?
考虑最后一个元素的下标 size - 1
那么父节点为 (size - 1) / 2
class Solution {
public int findKthLargest(int[] nums, int k) {
int size = nums.length;
buildHeap(nums, size);
for(int i = 0; i < k - 1; i++){
swap(nums, 0, size - 1);
size --;
maxHeapify(nums, 0, size);
}
return nums[0];
}
public void buildHeap(int[] nums, int size){
for(int i = size / 2 - 1; i >= 0; i--){
maxHeapify(nums, i, size);
}
}
public void maxHeapify(int[] nums, int i, int size){
int l = i * 2 + 1;
int r = i * 2 + 2;
int larger = i;
if(l < size && nums[l] > nums[larger])
larger = l;
if(r < size && nums[r] > nums[larger])
larger = r;
if(larger != i){
swap(nums, larger, i);
maxHeapify(nums, larger, size);
}
}
public void swap(int[] nums, int a, int b){
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
}
标签:215,nums,int,larger,中等,maxHeapify,数组,public,size
From: https://www.cnblogs.com/ganyq/p/18109149