题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
示例1
输入
1,2,3,4,5,6,7,0
输出
7
解题思路:
使用归并排序的思想,总之很麻烦。。
python solution:
# -*- coding:utf-8 -*-
class Solution:
def InversePairs(self, data):
return self.mergesort(data,0,len(data)-1)%1000000007
def mergesort(self,data,start,end):
if start>=end:
return 0
mid = (start+end)//2
leftcounts = self.mergesort(data,start,mid)
rightcounts = self.mergesort(data,mid+1,end)
import copy
cop = copy.deepcopy(data)
foreidx = mid
backidx = end
counts = 0
idxcopy = end
while foreidx>=start and backidx>=mid+1:
if data[foreidx]>data[backidx]:
cop[idxcopy] = data[foreidx]
idxcopy -= 1
foreidx -= 1
counts += backidx - mid
else:
cop[idxcopy] = data[backidx]
idxcopy -= 1
backidx -= 1
while foreidx>= start:
cop[idxcopy] = data[foreidx]
idxcopy -= 1
foreidx -= 1
while backidx>=mid+1:
cop[idxcopy] = data[backidx]
idxcopy -= 1
backidx -= 1
for i in range(start,end+1):
data[i] = cop[i]
return leftcounts+rightcounts+counts