avatar
an interview question# Programming - 葵花宝典
i*y
1
a. Given an array of n integers, can you write an algorithm that finds k
smallest numbers?
b. What is the complexity of your algorithm?
avatar
t*l
2
能想到最好的办法就是建立一个k-element的max-heap.复杂度是O(nlogk)

k

【在 i*****y 的大作中提到】
: a. Given an array of n integers, can you write an algorithm that finds k
: smallest numbers?
: b. What is the complexity of your algorithm?

avatar
s*u
3
k smallest numbers是nth_element的副产品

k

【在 i*****y 的大作中提到】
: a. Given an array of n integers, can you write an algorithm that finds k
: smallest numbers?
: b. What is the complexity of your algorithm?

avatar
j*g
4
same idea as quick sort.
Use a pivot p as comparison base. All numbers larger than p move to right,
smaller move to left. Recurse on either left side with (k) or right side
with (k - #

Worst case is n^2.
No time for average case, but I guess should be O(n).
avatar
N*n
5
A max-heap solution is faster than that.

【在 s****u 的大作中提到】
: k smallest numbers是nth_element的副产品
:
: k

avatar
p*n
6
why?

【在 N********n 的大作中提到】
: A max-heap solution is faster than that.
avatar
e*w
7
O(N) time to select the k-th smallest element X. (see CLRS)
O(N) time to scan the array and compare with X to get the k smallest numbers.

k

【在 i*****y 的大作中提到】
: a. Given an array of n integers, can you write an algorithm that finds k
: smallest numbers?
: b. What is the complexity of your algorithm?

avatar
e*e
8
第一步的副产品不就是答案了么?

numbers.

【在 e*****w 的大作中提到】
: O(N) time to select the k-th smallest element X. (see CLRS)
: O(N) time to scan the array and compare with X to get the k smallest numbers.
:
: k

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。