215.数组中的第K个最大元素
调用库函数
class Solution {
public int findKthLargest(int[] nums, int k) {
//匿名内部类
PriorityQueue<Integer> maxHeap=new PriorityQueue<>(new Comparator<>(){
//重写Comparator 中的方法
public int compare(Integer a,Integer b){
return b-a;
}
});
//元素都放入堆中
for(int x:nums)
maxHeap.offer(x);
//第k大的元素
for(int ee=0;ee<k-1;ee++)
maxHeap.poll();
return maxHeap.peek();
}
}
自己实现:
关键字:第K个
模式识别(使用方法):维护动态数据的最大最小值,可以考虑堆
建立容量为K的小顶堆(里面维护k个最大值)
方法三 大顶堆https://leetcode.cn/problems/kth-largest-element-in-an-array/solution/215-shu-zu-zhong-de-di-kge-zui-da-yuan-s-2zkk/
大根堆和堆排序:https://www.bilibili.com/video/BV1uu411i7ZL/?spm_id_from=autoNext&vd_source=755fa867364448953d97aa99efa2ec41
class Solution {
public int findKthLargest(int[] nums, int k) {
int heapSize = nums.length;
//构建大顶堆
buildMaxHeap(nums,heapSize);
//堆排序,把顶点处(最大)的换到最后的位置,其余接着进行堆排序
for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {
swap(nums, 0, i);
--heapSize;
maxHeapify(nums, 0, heapSize);
}
return nums[0];
}
public void buildMaxHeap(int[] a, int heapSize) {
//从第一个非叶子节点开始构建
for (int i = heapSize / 2; i >= 0; i--) {
//构建第i个节点的大顶堆
maxHeapify(a, i, heapSize);
}
}
public void maxHeapify(int[] a, int i, int heapSize) {
//i是作为顶点
//l和r是二叉树中的下标也是数组的数组中的下标
int l = i * 2 + 1;
int r = i * 2 + 2;
int largest = i;//i是顶点 暂时记录一下
//以下两步记录三个点中最大的点
if (l < heapSize && a[l] > a[largest]) {
largest = l;
}
if (r < heapSize && a[r] > a[largest]) {
largest = r;
}
//如果最大的点不是默认的i 则需要将最大点变成顶点
if (largest != i) {
//将i与largeset在数组中交换
swap(a, i, largest);
//递归交换后面的节点
maxHeapify(a, largest, heapSize);
}
}
public void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}