/*题目:在数组中的两个数字如果见面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求这个数组
中的逆序对的总数
*/
#include <iostream>
using namespace std;
int ReversePairsCore(int data[], int copy[], int start, int end)
{
//递归出口
if(start == end)
{
copy[start] = data[start];
return 0;
}
int length = (end - start) / 2;
//递归调用,并利用归并排序实现排序结排序好的结果放在data[]数组中,所以copy和data位置调换
//(递归时要用到copy数组作为中转将其转存到data中)。
//利用递归将数组分为两部分
int left = ReversePairsCore(copy, data, start, start + length);
int right = ReversePairsCore(copy, data, 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(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 left + right + count;
}
//
int ReversePairs(int data[], int length)
{
if(data == NULL || length < 0)
return 0;
int *copy = new int[length];
//初始化辅助数组为和data数组相同
for(int i = 0; i < length; ++i)
copy[i] = data[i];
int count = ReversePairsCore(data, copy, 0, length - 1);
delete [] copy;
return count;
}
//================测试代码=================
void Test(int data[], int length, int expected)
{
if(ReversePairs(data, length) == expected)
cout << "Passed!" << endl;
else
cout << "Failed!" << endl;
}
//=============================================
int main()
{
//递增数组
int data1[] = {1, 2, 3, 4, 5, 6};
int expected1 = 0;
Test(data1, sizeof(data1) / sizeof(int), expected1);
//递减数组
int data2[] = {6, 5, 4, 3, 2, 1};
int expected2 = 15;
Test(data2, sizeof(data2) / sizeof(int), expected2);
//未经排序的数组
int data3[] = {1, 2, 3, 4, 7, 6, 5};
int expected3 = 3;
Test(data3, sizeof(data3) / sizeof(int), expected3);
//数组中包含重复的数字
int data4[] = {1, 2, 1, 2, 1};
int expected4 = 3;
Test(data4, sizeof(data4) / sizeof(int), expected4);
//数组中只有两个数字,递增排序
int data5[] ={1, 2};
int expected5 = 0;
Test(data5, sizeof(data5) / sizeof(int), expected5);
//数组中只有两个数字, 递减排序
int data6[] = {2, 1};
int expected6 = 1;
Test(data6, sizeof(data6) / sizeof(int), expected6);
//数组中只有一个数字
int data7[] = {1};
int expected7 = 0;
Test(data7, sizeof(data7) / sizeof(int), expected7);
//输入空指针
Test(NULL, 0, 0);
return 0;
}
面试题36:数组中的逆序对
最新推荐文章于 2021-09-29 18:27:53 发布