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.找到数组a中第n/2小的数median;
2.对a中非median数进行|a[i] - median|,得到一个大小为n - 1的数组distance;
3.寻找distance中第k小的数值;
4.对distance进行一次遍历,找到小于等于k的数,从而对应得到数组a中的k个数。
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
可见可以在线形时间能得到集合S的K个最邻近点
转自:http://blog.csdn.net/pennyliang/article/details/1181890