此问题可转化为Top K问题进行考虑,当用小顶堆选出K个最大值时,堆顶的元素即为第k大的元素
class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int,vector<int>,greater<int> >q;//小顶堆 //priority_queue<int,vector<int>,less<int> >q;大顶堆 int len=nums.size(); for(int i=0;i<len;i++){ if(i<k) q.push(nums[i]); else{ if(q.top()<nums[i]){ q.pop(); q.push(nums[i]); } } } return q.top(); } };
自己重载比较运算符:
/** 建立一个小顶堆,每次出现新元素大于堆顶元素则替换堆顶元素 **/ class Solution { public: int findKthLargest(vector<int>& nums, int k) { vector<int> topk; struct cmp{ bool operator()(int a,int b){return a>b;}//小顶堆 }; priority_queue<int,vector<int>,cmp> q; for(int num:nums){ if(q.size()<k){ q.push(num);continue; } if(num>q.top()){ q.pop();q.push(num); } } return q.top(); } };