简体   繁体   English

基于索引查找列表中大于条件的对数的最佳代码?

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

Let's say A = [5,2,1,3], denote the number of pairs (i,j).假设 A = [5,2,1,3],表示对数 (i,j)。 1<=i < j<=n such that A[i]>A[j]. 1<=i < j<=n 使得 A[i]>A[j]。 Below is unoptimised code for same下面是相同的未优化代码


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

Looks like your problem is the inversion count, very famous in competitive programming, the optimal solution to this is using mergesort, you can find plenty of implementations on the internet, I like the one in geeksforgeeks: https://www.geeksforgeeks.org/counting-inversions/看起来你的问题是倒数,在竞争性编程中非常有名,对此的最佳解决方案是使用归并排序,你可以在互联网上找到很多实现,我喜欢 geeksforgeeks 中的一个: https ://www.geeksforgeeks.org /计数倒置/

The basic idea behind it is using divide and conquer, the article above explains the problem in a very good way.它背后的基本思想是使用分而治之,上面的文章很好地解释了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM