LeetCode solution to a problem | 215. Kth Largest Element in the k-th large number of an Array (heap C ++)

Title Description (medium difficulty)

Original title link
Here Insert Picture Description

algorithm

(Small root heap) THE ( n l The g k ) O(nlogk)

(1) using a small root heap, pile whenever there are k + 1 elements, it must not be the top of the stack k-th largest element
(2) traversing the nums array heap will last remaining k elements, At this time, the top element is nums array k-th largest number

Time complexity is O ( n l o g k ) O(nlogk) , the spatial complexity is O ( k ) O(k)

C ++ code 1

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int> > q;
        for (auto x : nums) {
            q.push(x);
            if (q.size() > k) q.pop();
        }
        return q.top();
    }
};

C ++ code 2

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        nth_element(nums.begin(), nums.begin() + n - k, nums.end());
        return nums[n - k];
    }
};

Reference material

[Daily] algorithm Day 82 classic interview question: seeking large numbers of K, I wrote 11 kinds of realization, not try it?

Published 308 original articles · won praise 149 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_43827595/article/details/104549613