zoukankan      html  css  js  c++  java
  • 算法导论习题[Exercises 9.37 ]

    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

  • 相关阅读:
    JDK6的switch支持不是很好
    团队作业(2)
    团队作业(1)
    4月30日
    重构:改善既有代码的设计有感
    4月28日
    4月27日
    4月26日
    4月25日
    4月24日
  • 原文地址:https://www.cnblogs.com/freewater/p/2170349.html
Copyright © 2011-2022 走看看