class Solution {
public int findKthLargest(int[] nums, int k) {
int heapSize = nums.length;
buildMaxHeap(nums);
//去除k-1个栈顶元素,那么此时位于栈顶的就是第k大的数
for(int i = 0;i < k-1;i++){
swap(nums,0,heapSize-1);
heapSize--;
maxHeapify(nums,0,heapSize);
}
return nums[0];
}
public void buildMaxHeap(int[] nums){
int heapSize = nums.length;
for(int i = heapSize/2 - 1;i >= 0;i--)
maxHeapify(nums,i,heapSize);
}
public void maxHeapify(int[] nums,int root,int heapSize){
while(root < heapSize/2){
int left = root * 2 + 1,right = root * 2 + 2;
int largest = left;
if(right < heapSize && nums[right] > nums[left])
largest = right;
if(nums[largest] <= nums[root])
break;
swap(nums,root,largest);
root = largest;
}
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}