立冬后 气温29度 天气晴 有蚊子
堆排序:数据结构-二叉堆&堆排序Java
题目
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
方法一:基于堆排序
代码
class Solution {
public int findKthLargest(int[] nums, int k) {
//基于堆排序的选择方法
int heapSize=nums.length;
buildMaxHeap(nums,heapSize);//构建一个大顶堆
//循环k-1次
for(int i=nums.length-1;i>=nums.length-k+1;--i){
swap(nums,0,i);//将堆顶元素放到最后
--heapSize;//堆大小-1,即删除原来的堆顶元素
maxHeapify(nums,0,heapSize);//重建堆
}
return nums[0];
}
public void buildMaxHeap(int[] a,int heapSize){
for(int i=heapSize/2;i>=0;--i){
maxHeapify(a,i,heapSize);
}
}
public void maxHeapify(int[] a,int i,int heapSize){
int l=i*2+1,r=i*2+2,largest=i;
if(l<heapSize&&a[l]>a[largest]){
largest=l;
}
if(r<heapSize&&a[r]>a[largest]){
largest=r;
}
if(largest!=i){
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;
}
}
复杂度
结果
方法二:小顶堆
分析
构造一个小顶堆,只存放k个元素。
遍历数组,向堆中添加。如果堆元素数量>k,则移除堆顶(即最小的元素)。遍历完后,堆中就是前k大的元素。堆顶就是第k大的元素。
代码
class Solution {
public int findKthLargest(int[] nums, int k) {
//小顶堆
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(nums.length);
for(int n:nums){
heap.add(n);
if(heap.size()>k)
heap.poll();
}
return heap.peek();
}
}
复杂度
时间复杂度:O(NlogK)。
空间复杂度:
结果
方法三:大顶堆
class Solution {
public int findKthLargest(int[] nums, int k) {
//大顶堆
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(nums.length,new Comparator<Integer>(){
public int compare(Integer i1 , Integer i2){
return i2 - i1;
}
});
//将元素不重复的加入堆中
for(int i:nums){
heap.add((Integer)i);
}
int i=0;
for(i=0;i<k-1;i++){
heap.poll();
}
return heap.poll();
}
}