【刷题剑指offer】数组中的逆序对
来源:互联网 发布:不可思议的植物 知乎 编辑:程序博客网 时间:2024/06/06 04:22
思路:先把数组分隔成子数组,统计出子数组内部的逆序对数目,然后再统计出两个相邻子数组之间的逆序对的数目,在统计逆序对的过程中,还需要对数组进行排序。如果对排序算法很熟练,我们不难发现这个排序的过程实际上就是归并排序。因此可以基于归并排序写出如下代码:
int InversePairs(int *data,int length) { if(data==NULL||length<0) return 0; int *copy=new int[length]; for(int i=0;i<length;i++) copy[i]=data[i]; int count=InversePairsCore(data,copy,0,length-1); delete[] copy; return count; } int InversePairsCore(int *data,int *copy,int start,int end) { if(start==end) { copy[start]=data[start]; return 0; } int length=(end-start)/2; int left=InversePairsCore(copy,data,start,start+length); int right=InversePairsCore(copy,data,start+length+1,end); //i初始化为前半段最后一个数字的下标 int i=start+length; //j初始化为后半段最后一个数字的下标 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=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; }
阅读全文
0 0
- 【刷题剑指offer】数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer 36 数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指Offer之 - 数组中的逆序对
- 剑指offer之数组中的逆序对
- 剑指offer 36 - 数组中的逆序对
- 《剑指offer》数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer—数组中的逆序对
- 【剑指offer】之数组中的逆序对
- 剑指offer:数组中的逆序对
- [剑指offer]数组中的逆序对
- 剑指offer:数组中的逆序对
- 剑指Offer--036-数组中的逆序对
- [剑指offer]数组中的逆序对
- 《剑指offer》:[36]数组中的逆序对
- 《剑指offer》-数组中的逆序对
- 类加载器ClassLoader
- iOS_nil、Nil、NULL、NSNull的区别
- 线性筛选求素数
- 笨方法学python(本文为阅读时从此书摘录的笔记) 第一天
- HDU 5810 Balls and Boxes (打表)
- 【刷题剑指offer】数组中的逆序对
- 图像识别--Java中使用openCV提取Hog特征通过SVM训练实现图像识别
- 17.7.13B组总结
- python3爬取淘宝信息!
- 树状数组总结——详解(单点/区间查询, 单点/区间修改, 逆序对)
- hdu 1698 (延迟标记+区间修改+区间求和)
- Codeforces #713C: Sonya and Problem without a Legend 题解
- POJ 1637 Sightseeing tour (欧拉路判定 网络流)
- windows上plsql连接linux虚拟机上oracle问题。