Consider a binary heap containing n numbers (the root stores the greatest number). You are given a positive integer k < n and a number x. You have to determine whether the kth largest element of the heap is greater than x or not. Your algorithm must take O(k) time. You may use O(k) extra storage
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- How to get a fixed number of evenly spaced points
- Space complexity of validation of a binary search
相关文章
- What is the complexity of bisect algorithm?
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- How to measure complexity of a string?
- Select unique/deduplication in SSE/AVX
Simple dfs can do it, we have a counter set to zero. Start from the root and in each iteration check the node value if is greater than x, then increase the counter and run algorithm for child nodes. When the counter is bigger or equal to k the algorithm will be finished, also if there is no node to check, algorithm returns false. The code is simple. The running time is O(k) because at most you will check k node and each iteration is O(1).
The pseudo-code looks like follows.
use it:
if node.value < x then all children values are smaller than x and there is no need to check.
As @Eric Mickelsen mentioned in comments worst case running time is exactly 2k-1 (k>0) as follows.
}