力扣215. 数组中的第K个最大元素

Problem: 215. 数组中的第K个最大元素

题目描述

在这里插入图片描述

思路

1.维护一个小顶堆minHeap,并将数组nums中的前k个元素添加到minHeap中;
2.从nums中k后面的元素开始,若当前nums中的元素大于小顶堆中的堆顶元素,则将其minHeap中堆顶的元素取出,将当前的nums中的元素添加到minHeap中
3.返回最终的minHeap堆顶的元素即为第K大元素;

复杂度

时间复杂度:

O ( n l o g n ) O(nlogn) O(nlogn);其中 n n n是数组的大小

空间复杂度:

O ( n ) O(n) O(n)

Code

class Solution {
public:
    int findKthLargest(std::vector<int>& nums, int k) {
        std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
        for (int i = 0; i < k; ++i) {
            minHeap.push(nums[i]);
        }
        // Starting from k, compare nums[i] with the top of the heap each time
        for (int i = k; i < nums.size(); i++) {
            int topElement = minHeap.top();
            // If it is larger than the top of the heap, the top of the heap element
            // is removed from the queue and the top element is rejoined.
            if (nums[i] > topElement) {
                minHeap.pop();
                minHeap.push(nums[i]);
            }
        }
        // Returns the smallest value in the smallest
        // heap of the largest k elements of the natural order
        return minHeap.top();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值