【问题标题】:Find the number of elements in the rest of the array that is greater than the element at each current position查找数组其余部分中大于每个当前位置的元素的元素数
【发布时间】:2015-05-15 19:48:39
【问题描述】:

假设给定一个一维数组:

[2, 3, 1, 5, 0, 2]

目标是构造另一个长度相同的数组,其中每个元素表示数组中大于当前数字的后续元素中的元素数量(不不同)。所以在我的情况下输出将是:

[2, 1, 2, 0, 1, 0]

O(n^2) 算法非常简单。什么是更有效的算法(最好在 Java 中)?

【问题讨论】:

  • 我想你可以向后遍历数组,然后创建一个新的排序列表。您使用的数字只是排序列表中该元素之后的元素数。您可能可以将其转换为 O(n*lg(n)) 算法
  • @SamIam OP 说他需要计算 后续 元素,而不是全部。排序会破坏顺序,因此不会保存子序列,所以我认为排序不是正确的解决方案
  • @FalconUA 看看他的例子中的第三个元素。他将1 映射到2,尽管最大的数字就在1 之后
  • 他没有映射任何东西,他的数组中的第三个元素只是后续大于1的元素数,所以我们只有2个元素:5和2.
  • @FalconUA 那么如何制作一个新的排序列表来阻止他这样做呢?

标签: java arrays algorithm count


【解决方案1】:

您可以使用 Fenwick tree 在 O(nlogn) 中执行此操作,这是一种保存直方图的数据结构,使得范围查询可以在 O(logn) 时间内完成。

简单地以相反的顺序遍历元素并将它们添加到直方图中。

Python 代码:

def fenwick_new(m):
    """Create empty fenwick tree with space for elements in range 0..m"""
    # tree[i] is sum of elements with indexes i&(i+1)..i inclusive
    return [0] * (m+1)

def fenwick_increase(tree,i,delta):
    """Increase value of i-th element in tree by delta"""
    while i < len(tree):
        tree[i] += delta
        i |= i + 1

def fenwick_sum(tree,i):
    """Return sum of elements 0..i inclusive in tree"""
    s = 0
    while i >= 0:
        s += tree[i]
        i &= i + 1
        i -= 1
    return s

def find_bigger(A):
    """Produce an array in which each element denotes the number of subsequent elements that are bigger"""
    top = max(A) + 1
    F = fenwick_new(top)
    B = []
    for n,a in enumerate(A[::-1]):
        count_of_bigger = n - fenwick_sum(F,a) # n is the number of things we have inserted into the tree so far
        B.append(count_of_bigger)
        fenwick_increase(F,a,1)
    return B[::-1]

A=[2,3,1,5,0,2]
print find_bigger(A)

(此算法草图仅在您的输入由具有合理上限的非负整数组成时才有效。如果您有更复杂的输入,请首先使用排序函数计算每个输入元素的排名。)

【讨论】:

  • 感谢算法草图。我对芬威克树不熟悉,我想我需要先研究一下。但是,是的,在我原来的问题中,输入也可以是负数。我会根据你的排名建议尝试用 Java 实现算法。
  • 你能详细解释一下这段代码吗?
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-11
  • 2017-05-29
  • 2015-01-31
相关资源
最近更新 更多