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];
}
相关推荐
祁思妙想17 分钟前
10.《滑动窗口篇》---②长度最小的子数组(中等)
leetcode·哈希算法
福大大架构师每日一题28 分钟前
文心一言 VS 讯飞星火 VS chatgpt (396)-- 算法导论25.2 1题
算法·文心一言
EterNity_TiMe_43 分钟前
【论文复现】(CLIP)文本也能和图像配对
python·学习·算法·性能优化·数据分析·clip
陌小呆^O^1 小时前
Cmakelist.txt之win-c-udp-client
c语言·开发语言·udp
机器学习之心1 小时前
一区北方苍鹰算法优化+创新改进Transformer!NGO-Transformer-LSTM多变量回归预测
算法·lstm·transformer·北方苍鹰算法优化·多变量回归预测·ngo-transformer
yyt_cdeyyds1 小时前
FIFO和LRU算法实现操作系统中主存管理
算法
alphaTao2 小时前
LeetCode 每日一题 2024/11/18-2024/11/24
算法·leetcode
kitesxian2 小时前
Leetcode448. 找到所有数组中消失的数字(HOT100)+Leetcode139. 单词拆分(HOT100)
数据结构·算法·leetcode
VertexGeek2 小时前
Rust学习(八):异常处理和宏编程:
学习·算法·rust
石小石Orz2 小时前
Three.js + AI:AI 算法生成 3D 萤火虫飞舞效果~
javascript·人工智能·算法