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];
}
相关推荐
wuyk5551 小时前
24. C 语言模块化:不是拆几个.c 文件那么简单
c语言·开发语言·stm32·单片机
qq_241585611 小时前
可用在中断中浮点数打印类似printf
c语言
凯瑟琳.奥古斯特2 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
Jerry2 小时前
LeetCode 203. 移除链表元素
算法
地平线开发者2 小时前
征程 6 | 工具链 QAT ObserverBase 源码解析
算法
C语言小火车3 小时前
C++ 快速排序(Quick Sort)深度精讲:分治思想、Lomuto 分区法及三数取中优化,面试手撕必会
c语言·开发语言·c++·面试·排序算法·快速排序
地平线开发者3 小时前
【地平线 征程 6 工具链进阶教程】QAT 训练常见问题和排查
算法
地平线开发者3 小时前
征程 6 | 直方图量化配置与校准实例
算法
地平线开发者3 小时前
征程 6E/M Matrix 开发评板使用系列(一):开箱与点亮
算法·自动驾驶