215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

Pick One


Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

**Note: **
You may assume k is always valid, 1 ≤ k ≤ array's length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


Seen this question in a real interview before? Yes

No
思路:用最小堆来实现, 当Q的size小于k时,就一直push,而后当堆顶元素小于遍历的nums[i],就给pop出去并且把nums[i] push进入堆中。
AC代码:

class Solution {
public:
    int findKthLargest(vector& nums, int k) {
        priority_queue,greater >Q;
        for(int i=0;i

你可能感兴趣的:(215. Kth Largest Element in an Array)