Leetcode 215 Kth Largest Element in an Array

1. 问题描述

  找出数组中第k大的数,注意:数组为无序数组。
  Leetcode 215 Kth Largest Element in an Array_第1张图片

2. 方法与思路

  是一道经典算法题。解法也有好几种,一种是先进行排序,然后取出第k大的数;由于排序算法最快效率为 O(nlogn) ,所以整体效率为 O(nlogn) 。二是使用优先队列,SLT中有优先队列的用法,内部是以堆的方式实现。时间效率也比较高, O(nlogn)
  

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

        for(auto &num:nums)
        {
            pq.push(num);
        }
        for(;k>1;k--) pq.pop();

        return pq.top();
    }
};

你可能感兴趣的:(LeetCode,算法,优先队列,第k最值)