[LeetCode]数组中的第K个最大元素

题目

 

 代码

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
       std::map<int,int,std::greater<int>> times;
       for(auto i :nums)
       {
           times[i]++;
       }
       for(auto i:times)
       {
           if(k<=i.second)
                return i.first;
           k-=i.second;
       }
       return 0;
    }
};

说明

利用底层为红黑树的map容器,内部使用std::greater自动按照大小进行排序,时间复杂度为O(nlogn), 当然,最简单的方法就是使用sort()去排序,然后很方便的获得第k个最大值,这里就不用最简单的方法了,提供一种新的思路。

https://github.com/li-zheng-hao
原文地址:https://www.cnblogs.com/lizhenghao126/p/11053597.html