【问题标题】:Finding which range of numbers has the most occurrence in a list查找列表中出现次数最多的数字范围
【发布时间】:2021-06-11 10:16:34
【问题描述】:

我必须遵循的复杂度是 o(n),所以我不允许使用嵌套循环。我对我想要做什么有一个粗略的想法,但是我不确定如何存储范围的下限。 目标是找到包含最多元素的区间的下限。 我们将 L 表示为范围的长度。我试过的是:

lst = [1,2,3,4,5,5,6,6,6,12] #after sorting by radix
L = 3

for i in range(len(lst)): 
    lower_bound[i] = i
    upper_bound[i] = i + L  #in this case L = 3.

    #if i is in range of certain i and its upper_bound,
    #increment count for that interval
    # e.g. 1 is in range of 0-3, so count for lower_bound[1] will +1.
    # e.g. 6 is in range of 4-6, so count for lower_bound[4] will +3.

#return the lower_bound with max count 

因此对于本例,将返回 3,因为 3-6 有 7 个元素(优先考虑最小下限)。 我不确定这是否是正确的方法:(这看起来是否正确,因为复杂度是 o(n)?

【问题讨论】:

  • 如果 n 表示列表的长度,那么不,它不是 o(n)。
  • 任务很不清楚,顺便说一句,最好添加适当的规范和示例。
  • 看起来你只是把它扔在这里然后马上走开了。我猜你毕竟对我们的帮助并不真正感兴趣。

标签: python algorithm sorting radix


【解决方案1】:

如果我正确理解您的问题,可能会使用两点方法解决。

将左指针(索引)设置为0,然后向右移动索引,直到lst[right]lst[left] 之间的元素差异大于L

记住索引差异right - left

向左移动索引直到元素差异小于L

再次向右移动索引,比较新索引与当前索引的差异,得到最大值。

重复直到列表结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2020-04-19
    • 2018-05-08
    • 2020-03-27
    • 2015-02-06
    相关资源
    最近更新 更多