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