【问题标题】:Find word with maximum number of occurrences查找出现次数最多的单词
【发布时间】:2018-09-23 00:36:53
【问题描述】:

在文档中搜索出现次数最多的单词的最佳方式(算法)是什么?

【问题讨论】:

  • 什么的最大出现次数?
  • 该文档中单词的最大出现次数
  • 您在寻找文档中出现次数最多的单词吗?一个简单的直方图可以在 O(n) 中解决问题。
  • 您还应该详细说明什么是“最有效”,大多数假设通常是指最快的平均情况,但它也可能意味着“占用空间更少”、最快的最坏情况、最简单的编码......
  • 在时间和记忆方面是最优的。我对在两者之间进行权衡的选项很好。

标签: algorithm find


【解决方案1】:
  1. 扫描文档一次,记录您看到每个唯一单词的次数(可能使用哈希表或树来执行此操作)。
  2. 在执行第 1 步时,跟踪目前所有单词中计数最多的单词。

【讨论】:

    【解决方案2】:

    通过简单的histogram [hash based] 可以在 O(n) 内找到文档中出现次数最多的单词:

    histogram <- new map<String,int>
    for each word in document: 
       if word in histogram:
          histogram[word] <- histogram[word] + 1
       else:
          histogram[word] <- 1
    max <- 0
    maxWord<- ""
    for each word in histogram:
      if histogram[word] > max:
         max <- histogram[word]
         maxWord <- word
    return maxWord
    

    这是 O(n) 的解决方案,而且由于问题显然是 Omega(n) 问题,所以就 big O notation 而言是最优的。

    【讨论】:

    • 最佳预期情况,无论如何。
    • A trie 代替哈希映射给出确定性 O(n) 最坏情况,但在实践中可能会更慢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多