【问题标题】:Finding the most frequent number from a set of ranges -从一组范围中找到最频繁的数字 -
【发布时间】:2012-12-31 05:08:58
【问题描述】:

问题如下:-

给你 N 头不同大象的寿命,用一对整数表示。

例如。 [5,10] [6,15] [2,7] 意思是,一头大象从 5 年到 10 年。第二只从 6 年到 15 年,依此类推..

你可以假设一头大象最多只能活 M 年。 (不是问题的一部分,但我们可能需要它来表示算法的复杂性。)

根据这些数据,找出最大数量的大象生活的年份。 随意解决关系。

我已经尝试了几种方法来解决这个问题,但似乎没有什么比简单解决方案的复杂性更重要的了。天真的解决方案是:-

1. Maintain an array(call it ctr).
2. For every set you encounter, 
    increment all values of ctr in that range.
3. Once you have traversed all sets, 
    find the index with the highest value in ctr.

很容易看出复杂度将是 O(N*M)。

谁能提供更好的解决方案?

另一个问题是:是否有一种数据结构可以在 O(1) 时间内更改一系列值?在数组中,要修改 k 个元素,显然需要 O(k) 时间。有更好的吗?

【问题讨论】:

    标签: algorithm computational-geometry


    【解决方案1】:

    将范围的左端视为 +1 大象活着,而将范围的右端视为 -1 大象活着。将这些 +1 和 -1 标记放在数轴上,然后在数轴上按从左到右的排序顺序排列。当你走在数轴上时,跟踪当前活着的大象数量(只需将 +1 和 -1 相加),并将其与活着的最大大象数量和相应年份进行核对。然后你就有了一个很好的 O(n log n) 时间解决方案。

    请注意,您必须在簿记方面小心一点,以便在当前年份处理 +1 之前的 -1,或者仅在处理给定年份内的所有数据后更新您的最大值。

    【讨论】:

    • 是的。那讲得通。谢谢。
    • :为什么我们需要按排序顺序进行?我们不能把 +1s 和 -1s 出现在数组中,然后遍历我们的新 ctr 数组。
    【解决方案2】:

    这是基于"scan line" trick在Python中实现@rrenaud's answer

    #!/usr/bin/env python
    ranges = [5,10], [6,15], [2,7]
    
    BORN, DIE = 1, 0 # values define sorting order within the same year
    events = sorted(event # sort start 'born' and end 'die' events together by year,
                          # process 'die' before 'born' in the same year
                    for r in ranges  for event in zip(r, (BORN, DIE)))
    
    max_nelephants = nelephants = 0
    prev_year = events[0][0]
    for year, born_or_die in events:
        if prev_year != year: # done processing a year
            prev_year = year
            max_nelephants = max(max_nelephants, nelephants)
        nelephants += (born_or_die == BORN) # increase number of alive elephants
        nelephants -= (born_or_die == DIE)  # decrease number of alive elephants
    max_nelephants = max(max_nelephants, nelephants)
    print(max_nelephants)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2021-07-14
      相关资源
      最近更新 更多