剑指offer-数组中的逆序对

29.数组中的逆序对

题目内容:

代码及思路:

1.如果遍历整个数组,对数组中的所有元素两两对比,那么该算法的复杂度是O(n^2)

2.利用归并排序的思想,进行拆解整合

#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
	int InversePairs(vector<int> data)
	{
		if (data.empty())
			return 0;
		int length = data.size();
		//创建一个辅助数组用来存放数字
		int* copy = new int[length];
		int* ori_data = &data[0];
		for (int i = 0; i < length; i++)
		{
			copy[i] = data[i];
		}
		//利用归并排序过程进行统计
		int count = InversePairscore(ori_data, copy, 0, length - 1);
		delete[] copy;
		return count;
	}
	int InversePairscore(int* data, int* copy, int start, int end) {
		if (start > end)
			return 0;
		//拆分为最小一个数字为基础单元
		if (start == end)
		{
			copy[start] = data[start];
			return 0;
		}
		int middle = start+(end - start) / 2;
		//对数组进行拆分
		int left = InversePairscore(copy, data, start, middle);
		int right = InversePairscore(copy, data,  middle + 1, end);
		//i初始化为前半段最后一个数字的下标,类似于图中标注的p1
		int i =  middle;
		//j初始化为后半段最后一个数字的下标,类似于图中标注的P2
		int j = end;
		//初始化辅助数组中的最后一个下标,类似于图中标注的p3
		int indexcopy = end;
		int count = 0;
		//按照图示的思路
		while(i >= start && j >= middle +1)
		{
			if (data[i] > data[j]) //产生逆序对,且逆序对的数目等于第二个数组中剩余数字的个数
			{
				copy[indexcopy--] = data[i--];
				count += j - middle;
			}
			else
			{
				copy[indexcopy--] = data[j--];
			}
		}
		while (i >= start)
		{
			copy[indexcopy--] = data[i--];
		}
		while (j >= middle + 1)
		{
			copy[indexcopy--] = data[j--];
		}
		return left + right + count;
	}
};
void main()
{
	vector<int> data;
	int num;
	char ch;
	do
	{
		cin >> num;
		data.push_back(num);
		cin.get(ch);
	} while (ch == ',');
	int count;
	Solution* object = new Solution;
	count = object->InversePairs(data);
	cout << count << endl;
	
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值