简体   繁体   中英

Is it possible to find the k-largest numbers from n unsorted integers with time complexity O(n) and space complexity O(k)?

I know that we can find the k-largest numbers from n unsorted integers in 2 ways:

  1. Use an algorithm like quick-select to find the Kth largest number, then we can get the k-largest numbers. The time complexity is O(n) and space complexity is O(n)
  2. Use a heap to store the k-largest numbers and iterate through n integers, then add proper integers to the heap. The time complexity is O(nlogk) and space complexity is O(k)

Suppose the n integers are in a stream and we don't have random access to them

I want to know is it possible to find the k-largest numbers from n unsorted integers with time complexity O(n) and space complexity O(k)?

It is. After filling the heap with k elements, instead of evicting one element from the heap after every insertion, evict k elements from the heap after every k insertions. Then you don't need the heap structure any more -- just select every time.

k次冒泡排序将在数组timeo(nk)的最后给出k个最大元素

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM