您的位置:首页 > Web前端

剑指Offer-51:数组中的逆序对

2018-03-15 11:37 381 查看

题目:

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。

例子:

如在数组{7,5,6,4}中,一共存在5个逆序对,分别是(7,6)、(7,5)、(7,4)、(6,4)、(5,4)。

链接:

剑指Offer(第2版):P249

思路标签:

算法:空间换时间归并排序

解答:

时间复杂度O(nlogn),空间复杂度O(n)

使用归并排序的思想,求每个子数组的逆序对;

先把数组分割成子数组,统计出子数组内部的逆序对的数目;

然后统计出两个相邻子数组之间的逆序对的数目;

在统计过程中,同时对数组进行排序。

需要一个辅助空间,来和原数组进行协同保存每个合并子数组的排序。

注意递归中传入参数copy和data互换。

class Solution {
public:
int InversePairs(vector<int> data) {
int length = data.size();
if (length <= 0)
return 0;

vector<int> copy;
for (int i = 0; i<length; ++i)
copy.push_back(data[i]);

long long count = InversePairsCore(data, copy, 0, length - 1);
return count % 1000000007;
}

long long InversePairsCore(vector<int> &data, vector<int> ©, int start, int end) {
if (start == end) {
copy[start] = data[start];
return 0;
}

int length = (end - start) / 2;

long long left = InversePairsCore(copy, data, start, start + length);
long long right = InversePairsCore(copy, data, start + length + 1, end);

int i = start + length;
int j = end;
int indexCopy = end;
long long count = 0;
while (i >= start && j >= start + length + 1) {
if (data[i] > data[j]) {
copy[indexCopy--] = data[i--];
count += j - start - length;
}
else {
copy[indexCopy--] = data[j--];
}
}

for (; i >= start; --i)
copy[indexCopy--] = data[i];
for (; j >= start + length + 1; --j)
copy[indexCopy--] = data[j];

return count + left + right;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息