簡體   English   中英

基於索引查找列表中大於條件的對數的最佳代碼?

[英]Optimal code to find the number of pairs with greater than condition in list based on index?

假設 A = [5,2,1,3],表示對數 (i,j)。 1<=i < j<=n 使得 A[i]>A[j]。 下面是相同的未優化代碼


def I(A):
    output = i = j = 0
    while i< len(A):
        j = i+1
        while j<len(A):
            if A[i]>A[j]:
                output +=1
            j+=1
        i+=1
    return output

看起來你的問題是倒數,在競爭性編程中非常有名,對此的最佳解決方案是使用歸並排序,你可以在互聯網上找到很多實現,我喜歡 geeksforgeeks 中的一個: https ://www.geeksforgeeks.org /計數倒置/

它背后的基本思想是使用分而治之,上面的文章很好地解釋了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM