Counting inversions in an array

前端 未结 30 2418
死守一世寂寞
死守一世寂寞 2020-11-22 04:14

I\'m designing an algorithm to do the following: Given array A[1... n], for every i < j, find all inversion pairs such that A[i] > A[j]

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:33

    Another Python solution, short one. Makes use of builtin bisect module, which provides functions to insert element into its place in sorted array and to find index of element in sorted array.

    The idea is to store elements left of n-th in such array, which would allow us to easily find the number of them greater than n-th.

    import bisect
    def solution(A):
        sorted_left = []
        res = 0
        for i in xrange(1, len(A)):
            bisect.insort_left(sorted_left, A[i-1])
            # i is also the length of sorted_left
            res += (i - bisect.bisect(sorted_left, A[i]))
        return res
    

提交回复
热议问题