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 <= numsi <= 10^4 −104<=numsi<=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];
}
相关推荐
2601_954526752 小时前
【工业传感与算法实战】温漂补偿与零点抗漂破局:基于二阶多项式拟合的 C/C++ 边缘校准算法,深度拆解“压力变送器什么牌子好”的技术硬指标
c语言·c++·算法
qq_448011163 小时前
C语言中的变量和函数的定义与声明
android·c语言·开发语言
叩码以求索3 小时前
浅谈:算法萌新如何高效刷题应对面试(一)
算法·面试·职场和发展
c238565 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
aaaameliaaa6 小时前
指针之总结
c语言·笔记·算法
宵时待雨6 小时前
优选算法专题9:哈希表
数据结构·算法·散列表
txzrxz6 小时前
最短路问题——Dijkstra 算法
数据结构·c++·算法·最短路·优先队列
gwf2166 小时前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
agathakuan7 小时前
Wireshark 解密並導出TLS 1.2 / TLS 1.3 明文的方法(可控制 Client 端)
c语言·wireshark·ssl·openwrt
caimouse7 小时前
protoc-gen-c 支持 proto3 `optional` 关键字修改记录
c语言·学习