Description
Given an integer array nums
and an integer k
, return the kth
, largest element in the array.
Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
Can you solve it without sorting?
Solution
Can you solve it without sorting?
Well, yes?
Here are two solutions:
- We could place all the element in a max heap then pop
k
elements to reach the kth largest element. (But we kind of heap sorted the array by this method :)) - Thank you STL.
Implementation
- Max heap
1 2 3 4 5 6 7 8 9 10 11 12
class Solution { public: int findKthLargest(std::vector<int> nums, int k) { priority_queue<int> heap(nums.begin(), nums.end()); int output = 0; for (int i = 0; i < k; i++) { output = heap.top(); heap.pop(); } return output; } };
- STL
std::nth_element
1 2 3 4 5 6 7
class Solution { public: int findKthLargest(std::vector<int> nums, int k) { nth_element(nums.begin(), nums.begin()+k-1, nums.end(), std::greater<int>()); return nums[k-1]; } };