Is the Time Complexity of this code O(N) ? (in this code I want to find Kth largest element of array)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
make_heap(nums.begin(), nums.end());
for (int i = 0; i < k - 1; i ++) {
pop_heap(nums.begin(), nums.end());
nums.pop_back();
}
return nums.front();
}
};
Because make_heap
is already at O(n), and each loop is at O(log n), the total time complexity for your algorithm is O(n + k log n) . With a small k or a "good" set of data, the result is roughly O(n) and the constant behind the O() mark, but with a large k (near or surpassing n/2) or random data, it's O(n log n).
Also I'd like to point out that this code is modifying the original array (using reference for passing arguments), which isn't often a good practice.
log is 2-based in this post
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.