#include <iostream>
//#include <string>
using namespace std;
//数组中的逆序对
//input: {7, 5, 6, 4}
//output: 5(分别是(7,5)、(7,6)、(7,4)、(5,4)、(6,4))
//时间复杂度为O(n2)
int InversePairs1(int* numbers, int length)
{
int count = 0;
for(int i=0; i<length-1; i++)
{
int j = i + 1;
for(; j<length; j++)
{
if(numbers[i] > numbers[j])
count++;
}
}
return count;
}
/*********************************************************
先把数组分割成子数组,先统计出子数组内部的逆序对的数目,
然后再统计出两个相邻子数组之间的逆序对的数目。统计逆序对
过程中,还需要对数组进行排序,不难发现,这个排序过程实际上
就是归并排序。
**********************************************************/
//时间复杂度为O(nlogn),空间复杂度O(n),利用空间消耗换来了时间效率的提升
int InversePairsCore(int* numbers, int* copy, int start, int end);
int InversePairs2(int* numbers, int length)
{
if(numbers == NULL || length < 0)
return 0;
int* copy = new int[length];
for(int i=0; i<length; i++)
copy[i] = numbers[i];
int count = InversePairsCore(numbers, copy, 0, length-1);
delete[] copy;
return count;
}
int InversePairsCore(int* numbers, int* copy, int start, int end)
{
if(start == end)
{
copy[start] = numbers[start];
return 0;
}
int length = (end - start)/2;
int left = InversePairsCore(numbers, copy, start, start + length);
int right = InversePairsCore(numbers, copy, start + length +1, end);
int i = start + length;
int j = end;
int indexCopy = end;
int count = 0;
while(i>=start && j>=start+length+1)
{
if(numbers[i] > numbers[j])
{
copy[indexCopy--] = numbers[i--];
count += j - start - length;
}
else
{
copy[indexCopy--] = numbers[j--];
}
}
for(; i>=start; --i)
copy[indexCopy--] = numbers[i];
for(; j>=start+length+1; --j)
copy[indexCopy--] = numbers[j];
return left + right + count;
}
int main()
{
int numbers[] = {7, 5, 6, 4};
int length = sizeof(numbers)/sizeof(int);
cout<<"InversePairs1:"<<InversePairs1(numbers, length)<<endl;
cout<<"InversePairs2:"<<InversePairs1(numbers, length)<<endl;
return 0;
}
数组中的逆序对
最新推荐文章于 2025-03-03 18:25:16 发布