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

  • 相关阅读:
    JavaScript 闭包究竟是什么
    Javascript闭包简单理解
    使用border做三角形
    负边距在布局中的使用
    direction和unicode
    CSS 实现打字效果
    你可能没注意的CSS单位
    前端模块化
    JavaScript面向对象
    阿里前端两年随想
  • 原文地址:https://www.cnblogs.com/freewater/p/2170349.html
Copyright © 2011-2022 走看看