python - 计数反转而不迭代两次

标签 python algorithm

问题可以查到here . 这是我尝试过的,但我得到了错误的答案。我的逻辑是这样的。在任何时候,如果排序队列和状态队列中的位置之间的差异为负,那么我们将差异的绝对值添加到混沌中。现在,如果我面临两个连续的正差异,并且前一个位置的数字大于状态队列中当前位置的数字,我将混沌加 1。

def minimumBribes(q):
    truth = None
    old = 0
    chaos = 0
    for i in range(len(q)):
        diff = (i+1)-q[i]
        if diff < -2:
            print("Too chaotic")
            return

        if diff < 0 :
            chaos = chaos + abs(diff)
            truth = True
            continue
        else:
            if truth == True:
                truth = False
                old = q[i]
                continue
            if old > q[i]:
                chaos = chaos + 1


        old = q[i] 
    print(chaos)

最佳答案

无法通过比较计算线性时间的倒置。它有一个理论上的界限。 https://cs.stackexchange.com/questions/74515/can-we-count-the-number-of-inversions-in-time-mathcalon

您可以使用 Fenwick Tree(也称为二叉索引树)求解。这里描述了这个想法(https://www.geeksforgeeks.org/count-inversions-array-set-3-using-bit/)。

关于python - 计数反转而不迭代两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52804242/

相关文章:

algorithm - 理解令人困惑的算法符号

python - 为什么 'pip show' 或 'pip list' 对我不起作用?

python - 使用 numpy.where 防止越界

algorithm - 查找表和动态规划

c - 确定恰好具有 4 个节点的子树数量的最佳方法是什么?

algorithm - 创建通过所有给定点的凹多边形

python - xlsxwriter 图表不显示?

python - 我需要编写一个正则表达式来识别所有以逗号分隔或不分隔的数字,不包括 4 位数字

python - 当 'go to declaration' 而不是使用其 remote_sources 中的一些过时的东西时,pycharm 不使用 vagrant box 中的 virtualenv

c++ - 一棵树上两片叶子的最低共同祖先