思路参考了另一篇博客,此处只是将原作者的代码翻译为Python版本:https://blog.csdn.net/lym940928/article/details/91354887
# -*- coding:utf-8 -*-
class Solution:
def InversePairs(self, data):
length=len(data)
if length<=0:
return 0
copy=[]
for i in range(length):
copy.append(data[i])
count=self.InverseHelper(data,copy,0,length-1)
return count%1000000007
def InverseHelper(self, data, copy, start, end):
if start==end:
copy[start]=data[start]
return 0
length=(end-start)/2
left=self.InverseHelper(copy,data,start,start+length)
right=self.InverseHelper(copy,data,start+length+1,end)
i=start+length
j=end
indexcopy=end
count=0
while i>=start and j>=start+length+1:
if data[i]>data[j]:
copy[indexcopy]=data[i]
indexcopy-=1
i-=1
count=count+j-start-length
else:
copy[indexcopy]=data[j]
indexcopy-=1
j-=1
while i>=start:
copy[indexcopy]=data[i]
indexcopy-=1
i-=1
while j>=start+length+1:
copy[indexcopy]=data[j]
indexcopy-=1
j-=1
return left+right+count