Describe an O(n)-time algorithm that, given a set S of n distinct numbers and a positive integer k ≤ n, determines the k numbers in S that are closest to the median of S.
solution:
1: procedure k_Closest(S, k) //S: a set of n numbers and k: an integer
2: Output = nothing;
3: m = Select(S, n,n/2) //O(n)
4: for all s in S and s != m //O(n)
5: s.distance = |m − s|
6: end for
7: md = Select(S.distance, k) //O(n)
8: for all s in S
9: if s.distance <= md.distance then //O(n)
10: Output = Output + s
11: end if
12: end for
13: return Output
14: end procedure
本文介绍了一种线性时间复杂度O(n)的算法,该算法能在给定的一组n个不同数值中找到距离中位数最近的k个数。通过一次遍历确定中位数,并计算每个数与中位数的距离,再次使用线性选择算法找出距离中位数最近的k个数。

被折叠的 条评论
为什么被折叠?



