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

  • 相关阅读:
    第一章复习(已完结)
    复习——第二章(施工完成,哪里总结的不全或是有问题欢迎指出)
    实验九
    实验五
    实验四
    实验三
    实验二
    实验一
    汇编语言第二章
    【C# 大写金额转阿拉伯数字】大写金额转数值
  • 原文地址:https://www.cnblogs.com/freewater/p/2170349.html
Copyright © 2011-2022 走看看