2024/9/20 LeetCode Hot100 堆第一题,最大堆解法

This commit is contained in:
Cool 2024-09-20 23:17:32 +08:00
parent dd6ea6ae2f
commit 361bd0ba38
1 changed files with 36 additions and 0 deletions

View File

@ -65,4 +65,40 @@ public class Num215 {
return quickSearch(nums, j + 1, right, k);
}
}
public int findKthLargest2(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];
}
private 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 left = 2 * i + 1, right = 2 * i + 2, largest = i;
if (left < heapSize && nums[left] > nums[largest]) {
largest=left;
}
if(right<heapSize&&nums[right]>nums[largest]){
largest=right;
}
if(largest!=i){
swap(nums,largest,i);
maxHeapify(nums,largest,heapSize);
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}