问题可以查到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/