code
//给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
//
// 请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
//
//
//
// 示例 1:
//
//
//输入: [3,2,1,5,6,4] 和 k = 2
//输出: 5
//
//
// 示例 2:
//
//
//输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
//输出: 4
//
//
//
// 提示:
//
//
// 1 <= k <= nums.length <= 10⁴
// -10⁴ <= nums[i] <= 10⁴
//
// Related Topics 数组 分治 快速选择 排序 堆(优先队列) 👍 1595 👎 0
class Solution {
public int findKthLargest(int[] nums, int k) {
class heap{
int size = 0;
int[] heapArr;
private heap(int capacity){ // 不要用 size ,easy 混淆,之前就错在,多写了一句 this.size = size;
this.heapArr = new int[capacity+1];
}
public boolean add(int k){
if(size > heapArr.length){
return false;
}
heapArr[++size] = k;
up(size);
return true;
}
private void up(int cur){
while((cur>>1) >= 1){
int parent = cur>>1;
if( heapArr[parent] > heapArr[cur] ){
int tem = heapArr[cur];
heapArr[cur] = heapArr[parent];
heapArr[parent]= tem;
cur = parent;
}else{
break;
}
}
}
public int pop(){
int returnVal = heapArr[1];
heapArr[1] = heapArr[size]; // 用size,别用heaparr.length-1
size--;
Down(size);
return returnVal;
}
private void Down(int size){
int cur = 1;
while((cur<<1) <= size){
int child = cur<<1;
if((child+1) <= size && heapArr[child+1] < heapArr[child]){
child++;
}
if( heapArr[cur] > heapArr[child]){
int tem = heapArr[cur];
heapArr[cur] = heapArr[child];
heapArr[child] = tem;
cur = child;
}else{
break; // 怎么少了break呢,太大意
}
}
}
public int peek(){
return heapArr[1];
}
}//end class heap
heap myheap = new heap(k);
for(int i=0; i<k; i++){
myheap.add(nums[i]);
}
for(int i=k; i< nums.length; i++){
if(nums[i] > myheap.peek()){
myheap.pop();
myheap.add(nums[i]);
}
}
return myheap.peek();
}
}```