LeetCode //C - 215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

Given an integer array nums and an integer k, return the k t h k^{th} kth largest element in the array.

Note that it is the k t h k^{th} kth largest element in the sorted order, not the k t h k^{th} kth distinct element.

Can you solve it without sorting?

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Constraints:
  • 1 < = k < = n u m s . l e n g t h < = 1 0 5 1 <= k <= nums.length <= 10^5 1<=k<=nums.length<=105
  • − 1 0 4 < = n u m s [ i ] < = 1 0 4 -10^4 <= nums[i] <= 10^4 −104<=nums[i]<=104

From: LeetCode

Link: 215. Kth Largest Element in an Array


Solution:

Ideas:

This function initializes a min heap with the first k elements of the array, then iterates through the rest of the array, maintaining the heap property and ensuring that only the k largest elements are in the heap. The k t h k^{th} kth largest element is then the smallest element in this heap.

Code:
c 复制代码
void minHeapify(int* heap, int heapSize, int i) {
    int smallest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < heapSize && heap[left] < heap[smallest])
        smallest = left;

    if (right < heapSize && heap[right] < heap[smallest])
        smallest = right;

    if (smallest != i) {
        int temp = heap[i];
        heap[i] = heap[smallest];
        heap[smallest] = temp;

        minHeapify(heap, heapSize, smallest);
    }
}

void buildMinHeap(int* heap, int heapSize) {
    for (int i = heapSize / 2 - 1; i >= 0; i--)
        minHeapify(heap, heapSize, i);
}

int findKthLargest(int* nums, int numsSize, int k) {
    int heap[k];
    for (int i = 0; i < k; i++)
        heap[i] = nums[i];

    buildMinHeap(heap, k);

    for (int i = k; i < numsSize; i++) {
        if (nums[i] > heap[0]) {
            heap[0] = nums[i];
            minHeapify(heap, k, 0);
        }
    }

    return heap[0];
}
相关推荐
水蓝烟雨20 分钟前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事27 分钟前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解38 分钟前
C++类和对象(上)
开发语言·c++·算法
JKHaaa1 小时前
几种简单的排序算法(C语言)
c语言·算法·排序算法
让我们一起加油好吗1 小时前
【基础算法】枚举(普通枚举、二进制枚举)
开发语言·c++·算法·二进制·枚举·位运算
FogLetter1 小时前
微信红包算法揭秘:从随机性到产品思维的完美结合
算法
BUG收容所所长2 小时前
二分查找的「左右为难」:如何优雅地找到数组中元素的首尾位置
前端·javascript·算法
itsuifengerxing2 小时前
python 自定义无符号右移
算法
猎板PCB厚铜专家大族3 小时前
高频 PCB 技术发展趋势与应用解析
人工智能·算法·设计规范
dying_man3 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode