https://leetcode.com/problems/kth-largest-element-in-an-array/

使用堆,堆插入一个数据是logk,删除一个数据是logk,复杂度为logk

Java

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> minQueue = new PriorityQueue<>(k);
          for (int num : nums) {
            if (minQueue.size() < k || num > minQueue.peek())
              minQueue.offer(num);
            if (minQueue.size() > k)
              minQueue.poll();
          }
          return minQueue.peek();
    }
}

C++的

class Solution
{
public:
    int findKthLargest(vector<int>& nums, int k)
    {
        priority_queue<int, vector<int>, greater<int> >pq;
        for(auto num:nums)
        {

            if(pq.size()<k)
                pq.push(num);
            else if(num>pq.top())
                pq.pop(),pq.push(num);
        }
        return pq.top();
    }
};

 使用快速选择,就是用快排改的,将数组分组,但是这个也是一个不稳定的做法

 

相关文章:

  • 2021-12-02
  • 2021-12-16
  • 2021-08-04
  • 2021-10-07
  • 2021-06-26
  • 2021-09-10
  • 2022-12-23
猜你喜欢
  • 2022-02-20
  • 2020-06-30
  • 2022-02-21
  • 2021-10-16
  • 2021-10-30
  • 2021-05-14
  • 2022-12-23
相关资源
相似解决方案