51-Reversed pairs in an array-python

Question: Two numbers in the array, if the first number is greater than the following number, then these two numbers form a reverse pair. Enter an array and find the reverse pairs in this array.

def inverse_pairs(arrys):
    if len(arrys)<2:
        return 0

    res = 0
    length = len(arrys)
    arrys_sort =sorted(arrys)
    for arr in arrys_sort:
        res += arrys.index(arr)
        arrys.remove(arr)

    return res

  Note: The official method is to use merge sort, and the time complexity is O(nlgn). This article gives its own method, the time complexity is O(n2), it needs to be improved, but the implementation is very concise. Sort the array first, using the built-in sort function. Then traverse the sorted array one by one, and find the index of the number in the original array one by one, and the index difference is the number of inverse pairs with the number.

Guess you like

Origin blog.csdn.net/wh672843916/article/details/105503748