string - 从文件中读取 URL 字符串列表并查找前 10 个最常阅读的 URL

标签 string algorithm url data-structures

<分区>

好的,

我在很多面试中都遇到过这个问题,我想我需要一些帮助来解决它。

您有大量的 URL 可以作为字符串数组或从文件中读取。您现在需要获取前 10 个最常阅读的网址,如文件中前 10 个最常用的 URL。

我的方法是:

         Read them into a String Array, 
         Iterate through each String/URL,
             At every Iteration, put them into Hashtable, incrementing the count.
         Iterate again and find feed the scores into an array
         Sort and find the top 10 scores OR use max-heap to get the top 10.
         Iterate again and remove the URL's with the top 10 scores.

这是一个非常糟糕的答案吗?有人可以进一步帮助我吗?

最佳答案

您可以使用最少的内存和基本上无限大小的文件来执行此操作:

Use the OS-supplied sort utility to sort the URLs on disk
Create a priority queue (binary heap, for example)
For each URL in the file
    if the URL is the same as the previous URL
        increase count
    else
        AddToQueue(previous_url, count)
        previous_url = current_url
        count = 1
EndFor
AddToQueue(previous_url, count)

此时,前 10 个访问量最大的 URL 将进入优先队列。

AddToQueue 函数如下所示:

AddToQueue(url, count)
    if (queue.Count < 10)
        add new url with count to queue
    else if (count > top_of_queue.count)
        remove top URL from queue
        add new url with count to queue

如果您有足够的内存来加载所有 URL,您可以将它们加载到一个数组中并对其进行排序。但是,如果您有足够的内存来存储所有 URL,那么基于字典的方法可能会更快。

关于string - 从文件中读取 URL 字符串列表并查找前 10 个最常阅读的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18936381/

相关文章:

javascript - 为什么 Javascript ===/== 字符串相等有时具有常数时间复杂度,有时具有线性时间复杂度?

python - 从簇中返回面积最大的圆

php - 对可能不包含协议(protocol)的字符串运行 parse_url()

javascript - 根据 url 参数设置 Cookie

python - 如何从包含 header 和正文的响应中提取 JSON 数据?

C:如何以更简洁的方式将空终止符复制到结构成员?

python - 将 Matlab 代码翻译为 Python

java - Hadoop gzip 压缩文件

php - 加密数字 URL 参数,结果不能比原来长

c++ - 如何为我的自定义 C++ 类实现复制构造函数