当前位置:网站首页>The largest kth element in the array

The largest kth element in the array

2022-06-11 02:14:00 Lingling Ling

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/kth-largest-element-in-an-array

Title Description :

Given an array of integers nums And integer k, Please return the... In the array k The biggest element .
Please note that , What you need to look for is the number after array sorting k The biggest element , Not the first. k A different element .

Input :

[3,2,1,5,6,4] and k = 2

Output :

5

Their thinking ( This solution is relatively optimized ):

  1. utilize priority_queue Build a pile
  2. priority_queue The default is to create a large number of
  3. By destacking , You can find the data
class Solution {
    
public:
    int findKthLargest(vector<int>& nums, int k) {
    
    // Method 1 : Prioritize , Ascending , Look forward 
    // Time complexity :O(N*logN)
       // sort(nums.begin(),nums.end());
       // return nums[nums.size()-k];

       // Method 2 : Prioritize , Using template parameters , Sort directly in descending order , Look from front to back 
       // Time complexity :O(N*logN)
       //sort(nums.begin(),nums.end(),greater<int>());
       //return nums[k-1];

	// Method 3 : Put the data in priority_queue in , Before deleting again k-1 Number 
	// Time complexity :O(N+K*logK)
	// if N Far greater than K, This method is more applicable 
		//priority_queue<int> p(nums.begin(),nums.end())
		//for(int i = 0; i < k-1; i++)
		//{
    
		// p.pop();
		//}
		//return p.top();

	// Method four :
       // structure k A few small piles , optimization 
       // Time complexity :O(K+(N-K)*logK)
        priority_queue<int,vector<int>,greater<int>> KMinHeap(nums.begin(),nums.begin()+k);
        for(size_t i = k; i < nums.size(); ++i)
        {
    
             if(nums[i] > KMinHeap.top())
             {
    
                 KMinHeap.pop();
                 KMinHeap.push(nums[i]);
             }
        }
        return KMinHeap.top();

    }
};
原网站

版权声明
本文为[Lingling Ling]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020617115902.html