problem
solution
option 1 - sort
1 | class Solution { |
option 2 - heap
- version 1
1
2
3
4
5
6
7
8
9
10
11
12
13class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> pq;
for(int n:nums) pq.push(n);
int ret ;
while(k--){
ret = pq.top();
pq.pop();
}
return ret;
}
}; - version 2
1
2
3
4
5
6
7
8
9
10
11class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for(int n:nums){
pq.push(n);
if(pq.size() > k) pq.pop();
}
return pq.top();
}
};
option 3 - quick sort
1 | class Solution { |
analysis
- option 1 - sort
- time complexity
O(nlogn)
- space complexity
O(n)
- time complexity
- option 2 - heap
- time complexity
O(nlogk)
- space complexity
O(k)
- time complexity
- option 3 - quick sort
- time complexity
O(nlogn)
on average,O(n^2)
on worse case - space complexity
O(n)
- time complexity