In an integer array with N elements , find the minimum k elements? [duplicate]

ⅰ亾dé卋堺 提交于 2020-02-07 05:23:04

问题


Possible Duplicate:
Worst-case O(n) algorithm for doing k-selection

Given the following question :

In an integer array with N elements , find the minimum k elements (k << N)

You can assume that N is a large number.

I'm thinking about a minimum heap , anyone has a better solution ?

Regards


回答1:


If K << N, min heap is good enough because creation of heap is O(n), and if K << N selecting first K items is at most O(N), otherwise you could use selection algorithm to find Kth smallest element in O(n) then select numbers which are smaller than found item. (Sure if some numbers are equal to Kth element select till fill K items).




回答2:


What about this:

Sort the array (quicksort or heapsort are great for integer arrays), and iterate to k




回答3:


I think you can do this one in O(N*log(K)). Pseudocode:

haz array[N]
haz output[k] (itz a list)

i iteratez on array with array[N] az element:
    i insertz element into output (i maintainz strict ordering)
    i removez largest element of output when output size iz bigger than k

Requires:

  • N list removals from end (N * O(1))
  • at most N sort-maintaining list inserts (N * O(log(listsize)))

list's size is bounded by K

Thus, O(N * log(K)) time.



来源:https://stackoverflow.com/questions/12057195/in-an-integer-array-with-n-elements-find-the-minimum-k-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!