problem Ⅰ
215. Kth Largest Element in an Array
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.
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
solution 1
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for(auto it : nums){
pq.push(it);
if(pq.size() > k) pq.pop();
}
return pq.top();
}
};
NOTE:
time complexity
:
O
(
n
)
∗
O
(
l
o
g
k
)
=
O
(
n
l
o
g
k
)
O(n)*O(logk) = O(nlogk)
O(n)∗O(logk)=O(nlogk)
space complexity
:
O
(
k
)
O(k)
O(k)
as we known, the time complexity of the operation like insert and pop in min/max heap is
O
(
l
o
g
n
)
O(logn)
O(logn), while the size of the heap is n.,and the space complexity is
O
(
n
)
O(n)
O(n).
so it is clear that why the time complexity of this algorithm is O ( n ∗ l o g k ) O(n*logk) O(n∗logk), cause we have to insert n elements into the priority queue, and every insert cost O ( l o g k ) O(logk) O(logk), while the priority queue’s max size is k
problem Ⅱ
347. Top K Frequent Elements
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
solution
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> maps;
for(auto it : nums)
maps[it]++;
priority_queue<pair<int, int>> pq;
for(auto it : maps)
pq.push({it.second, it.first});
vector<int> res;
while(k--){
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};
NOTE:
time complexity
:
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)
because the unordered_map is implemented using hash table, so the TC of insert operation in unordered_map is O ( 1 ) O(1) O(1) on average and O ( n ) O(n) O(n) worst case, so the TC of constructing a unordered_map is O ( n ) ∗ O ( 1 ) = O ( n ) O(n)*O(1)=O(n) O(n)∗O(1)=O(n)
the TC of constructing a priority_queue is O ( n ) ∗ O ( l o g n ) = O ( n l o g n ) O(n)*O(logn)=O(nlogn) O(n)∗O(logn)=O(nlogn)
the TC of geting the result is O ( k l o g n ) O(klogn) O(klogn)
so the total TC is O ( n ) + O ( n l o g n ) + O ( k l o g n ) = O ( n l o g n ) O(n)+O(nlogn)+O(klogn)=O(nlogn) O(n)+O(nlogn)+O(klogn)=O(nlogn)
space complexity
:
O
(
n
)
+
O
(
n
)
=
O
(
n
)
O(n)+O(n) = O(n)
O(n)+O(n)=O(n)