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 sin Sand s != m //O(n)
5: s.distance = |m − s|
6: end for
7: md = Select(S.distance, k) //O(n)
8: for all sin 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个数。算法首先通过Select过程找到中位数,然后计算每个数与中位数的距离,并再次使用Select过程找到这些距离中的第k小的数作为阈值。最后,所有与中位数距离小于等于该阈值的数即为所求。
1475

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



