版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014568072/article/details/87890442
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
样例
输入
1,2,3,4,5,6,7,0
输出
7
思路
《剑指offer》P189
采用归并排序的思想,递归地将数组分为左右两边,统计左边相对于右边的逆序对数目,同时合并两个子数组并排序。
code
class Solution {
public:
int InversePairs(vector<int> data) {
if (data.size() == 0)
return 0;
vector<int> copydata;
for (int i = 0; i < data.size(); i ++)
copydata.push_back(data[i]);
long long res = InversePairsCore(data, copydata, 0, data.size() - 1);
return res % 1000000007;
}
int InversePairsCore(vector<int> &data, vector<int> ©data, int start, int tend) {
if (start == tend) {
copydata[start] = data[start];
return 0;
}
int mid = (tend - start) / 2;
long long left = InversePairsCore(copydata, data, start, start + mid);
long long right = InversePairsCore(copydata, data, start + mid + 1, tend);
int i = start + mid;
int j = tend;
int index = tend;
long long cnt = 0;
while (i >= start && j >= start + mid + 1) {
if (data[i] > data[j]) {
copydata[index--] = data[i--];
cnt += (j - start - mid);
}
else
copydata[index--] = data[j--];
}
while (i >= start)
copydata[index--] = data[i--];
while (j >= start + mid + 1)
copydata[index--] = data[j--];
return (left + right + cnt) % 1000000007;
}
};
python版本的代码一直提示运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。 case通过率为75.00%
,但是就本方法而言感觉找不到能够优化的地方了。下面也贴上代码。
# -*- coding:utf-8 -*-
import copy
class Solution:
def InversePairs(self, data):
if not data:
return 0
copydata = copy.deepcopy(data)
return self.InversePairsCore(data, copydata, 0, len(data) - 1)
def InversePairsCore(self, data, copydata, start, end):
if start == end:
copydata[start] = data[start]
return 0
mid = (end - start) / 2
left = self.InversePairsCore(copydata, data, start, start + mid)
right = self.InversePairsCore(copydata, data, start + mid + 1, end)
i = start + mid
j = end
index = end
cnt = 0
while i >= start and j >= start + mid + 1:
if data[i] > data[j]:
cnt += (j - start - mid)
copydata[index] = data[i]
index -= 1
i -= 1
else:
copydata[index] = data[j]
index -= 1
j -= 1
while i >= start:
copydata[index] = data[i]
index -= 1
i -= 1
while j >= start + mid + 1:
copydata[index] = data[j]
index -= 1
j -= 1
# data = copy.copy(copydata)
return (right + left + cnt) % 1000000007