题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
例如在数组{7, 5, 6, 4}中,总共存在5个逆序对,分别为{7, 6}、{7, 5}、{7, 4}、{6, 4}、{5, 4}。
解法一:暴力搜索
顺序扫描数组,没扫描到一个数字时,将该数字后面的数字逐个与该数字进行比较,如果后面的数字比该数字小,则这两个数字组成一个逆序对。这种算法的时间复杂度为O(n*n)。
解法二:
《剑指offer》书中的方法,我们以{7, 5, 6, 4}为例来分析统计逆序对的过程。每次扫描到一个数字的时候,不能拿它和后面的每一个数字进行比较,否则时间复杂度为O(n*n)。我们可以考虑分割子问题,把待统计数组分为两个数组,分别统计两个子数组中存在的逆序对,然后再统计两个子数组对之间的逆序对,该算法时间复杂度为O(n*logn)。
原文代码有bug,勘误后的代码:
/**
* 2014-06-28
*/
#include <iostream>
using namespace std;
int InversePairsCore(int data[], int copy[], int start, int end)
{
if (start == end)
return 0;
int mid = (start + end) / 2;
int leftCount = InversePairsCore(data, copy, start, mid);
int rightCount = InversePairsCore(data, copy, mid + 1, end);
int count = 0;
int i = mid, j = end, last = end;
while (i >= start && j > mid)
{
if (data[i] > data[j])
{
count += (j - mid);
copy[last--] = data[i--];
}
else
{
copy[last--] = data[j--];
}
}
while (i >= start)
copy[last--] = data[i--];
while (j > mid)
copy[last--] = data[j--];
// ! copy the copy[] to data[]
for (i = start; i <= end; ++i)
data[i] = copy[i];
return count + leftCount + rightCount;
}
int InversePairs(int data[], int n)
{
// n <= 0
if (data == NULL || n <= 0)
return 0;
int *copy = new int[n];
for (int i = 0; i < n; ++i)
copy[i] = data[i];
int count = InversePairsCore(data, copy, 0, n - 1);
delete [] copy;
return count;
}
int main()
{
//int A[4] = {7, 5, 6, 4};
//int A[8] = {7, 5, 6, 4, 9, 2, 3, 1};
int A[5] = {1, 2, 1, 2, 1};
cout << InversePairs(A, 5) << endl;
return 0;
}