1.题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
2.解题思路
归并思想
解法二:但是在牛客网的时间复杂度超时
参考:https://blog.youkuaiyun.com/lzq20115395/article/details/79554591
3.代码实现
class Solution:
def InversePairs(self, data):
# write code here
length = len(data)
if length == 0 or length == 1:
return 0
copy = data[:]
count = self.Core(data, copy, 0, length - 1)
print count
return count
def Core(self, d, copy, start, end):
if start == end:
return 0
length = (end-start) // 2
i = start + length
j = end
left = self.Core(d, copy, start, i)
right = self.Core(d, copy, i + 1, end)
index = end
count=0
while i >= start and j >= start + length + 1:
if d[i] > d[j]:
count += j - (start + length)
count%=1000000007
copy[index] = d[i]
index -= 1
i -= 1
else:
copy[index] = d[j]
index -= 1
j -= 1
if i >= start:
for t in range(i, start-1, -1):
copy[index] = d[t]
index -= 1
if j >= start + length + 1:
for t in range(j, start + length, -1):
copy[index] = d[t]
index -= 1
for t in range(start,end+1):
d[t]=copy[t]
return (left + right + count)%1000000007