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];
}
相关推荐
强盛小灵通专卖员3 小时前
分类分割详细指标说明
人工智能·深度学习·算法·机器学习
IT猿手6 小时前
基于强化学习 Q-learning 算法求解城市场景下无人机三维路径规划研究,提供完整MATLAB代码
神经网络·算法·matlab·人机交互·无人机·强化学习·无人机三维路径规划
czy87874757 小时前
C语言主要标准版本的演进与核心区别的对比分析
c语言
巨龙之路8 小时前
C语言中的assert
c语言·开发语言
万能程序员-传康Kk10 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球10 小时前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll77881110 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~10 小时前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子10 小时前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
阳洞洞10 小时前
leetcode 18. 四数之和
leetcode·双指针