数组中的逆序对 —— 《剑指offer》第36题勘误

题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

例如在数组{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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值