堆排序的思路:
1.构造初始堆。将给定无序序列构造成一个大顶堆
2.将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端;
3.重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整+交换步骤,直到整个序列有序。
思路:堆排序,大根堆用于升序,小根堆用于降序。注意循环次数,应该是 k - 1 次,比如 k = 2,那么应该删除 1 次
也可以用直接用堆做。
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; i--){
swap(nums, 0, i);
heapSize--;
maxHeapify(nums, 0, heapSize);
}
return nums[0];
}
public void buildMaxHeap(int[] nums,int heapSize){
// 从最后一个非叶子结点开始,建堆。
for(int i = heapSize / 2; i >= 0; i--){
maxHeapify(nums, i, heapSize);
}
}
public void maxHeapify(int[] nums, int i ,int heapSize){
int l = 2 * i + 1, r = 2 * i + 2, largestIndex = i;
if(l < heapSize && nums[l] > nums[largestIndex]){
largestIndex = l;
}
if(r < heapSize && nums[r] > nums[largestIndex]){
largestIndex = r;
}
if(largestIndex != i){
swap(nums, i, largestIndex);
maxHeapify(nums, largestIndex, heapSize);
}
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
使用堆来做,维护一个k大小的最小堆。
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0; i < k; i++){
pq.offer(nums[i]);
}
for(int i = k; i < nums.length; i++){
if(nums[i] > pq.peek()){
pq.poll();
pq.offer(nums[i]);
}
}
return pq.peek();
}
}
只用一个for循环,动态选出第k大的值。
跟上种方式的区别:每个 num[i] 都加入堆,而上面是只有nums[i] > pq.peek()
才加入堆。
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0; i < nums.length; i++){
pq.offer(nums[i]);
// 此时有 k+1 个元素,弹出堆顶元素
if(pq.size() > k){
pq.poll();
}
}
// 最后小顶堆只剩 k 个元素,返回堆顶元素
return pq.peek();
}
}