在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。
用类似归并排序的思路。
# -*- coding:utf-8 -*-
class Solution:
def InversePairsCore(self, data, copy, start, end):
if start == end:
copy[start] = data[start]
return 0
length = int((end - start) / 2)
left = self.InversePairsCore(copy, data, start, start + length)
right = self.InversePairsCore(copy, data, start + length + 1, end)
i = start + length
j = end
copy_index = end
counter = 0
while (i >= start) and (j >= start + length + 1):
if data[i] > data[j]:
counter += j - start - length
copy[copy_index] = data[i]
copy_index -= 1
i -= 1
else:
copy[copy_index] = data[j]
copy_index -= 1
j -= 1
while i >= start:
copy[copy_index] = data[i]
copy_index -= 1
i -= 1
while j >= start + length + 1:
copy[copy_index] = data[j]
copy_index -= 1
j -= 1
return (left + right + counter) % 1000000007
def InversePairs(self, data):
# write code here
if data:
copy = [item for item in data]
return self.InversePairsCore(data, copy, 0, len(data) - 1)
else:
return 0
这道题牛客不知道是不是抽风了,python永远报超时…