[Daily question] 24: The Kth largest element in the array

Title description

Find the k-th largest element in the unsorted array. Note that what you need to find is the k-th largest element after the array is sorted, not the k-th different element.

Example 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

Explanation:

You can assume that k is always valid, and 1 ≤ k ≤ the length of the array.

Violence law

Demo code:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        if(nums.size() < k || nums.size() == 0){
            return 0;
        }
        sort(nums.begin(), nums.end());
        return nums[nums.size() - k];
    }
};

Use a small top pile

Demo code:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        if(nums.size() < k || nums.size() == 0){
            return 0;
        }

        priority_queue<int, vector<int>, greater<int>> pq;

        for(int i = 0; i < nums.size(); i++)
        {
            pq.push(nums[i]);
            if (int(pq.size()) > k)
            {
                pq.pop();
            }
        }
        
        return pq.top();
    }
};

Use a large top pile

Demo code:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        if(nums.size() < k || nums.size() == 0){
            return 0;
        }
        
        int i;
        priority_queue<int> p(nums.begin(), nums.end());
        // 将优先级队列中前k-1个元素删除掉 
        //priority_queue<int, vector<int>, less<int>> pq;

        //for(i = 0; i < nums.size(); i++){
        //    pq.push(nums[i]);
        //}
        for(i = 1; i < k; i++){
            pq.pop();
        }
        return pq.top();
    }
};

If you have different opinions, please leave a message to discuss! ! !

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105369770