剑指offer——数组中的逆序对
2016-07-27 21:40
441 查看
题目描述:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
思路:
要找到数组中的逆序对,一种思路是每遍历到一个元素的时候就和后面的元素进行一一比较,这种算法的时间复杂度是O(n2),所以不是很理想。我们可以借鉴归并排序的思想,把数组划分为子数组,然后对每个子数组中的逆序对数进行统计,统计完成后再并到一个新的数组中进行统计,这样就化整为零,实现了高效统计。总计起来思路就是:首先把数组划分为子数组,然后统计子数组中的逆序对数,然后继续统计相邻子数组的逆序对数,在统计相邻子数组中的逆序对数的时候,需要使用两个指针,一个指向第一个数组的头部,一个指向第二个数组的头部,如果第一个指针指向的元素大于后面的,说明相邻之间存在逆序对,并把较大的那个数拷贝到一个临时数组中,然后指针往前移动,直到所有的子数组以及相邻的子数组的逆序对数统计完毕。代码实现:
public class Solution { int resultCount = 0; // 逆序对的数量 public int InversePairs(int[] array) { int len = array.length; int first = 0; int last = len - 1; int temp[] = new int [len];// 辅助数组,用以保存合并后的数组 mergeSort(array, first, last, temp); return resultCount%1000000007 ; } private void mergeSort(int[] array, int first, int last, int[] temp) { if(first < last){ int mid = (first + last) / 2; mergeSort(array, first, mid, temp);// 左子数组有序 mergeSort(array, mid+1, last, temp);// 右子数组有序 mergeArray(array, first, mid, last, temp); // 合并数组 } } // 合并两个有序数组 private void mergeArray(int[] array, int first, int mid, int last, int[] temp) { int lFirst = first, lLast = mid; // 左子数组的首尾标识; int rFirst = mid + 1, rLast = last; // 右子数组的首尾标识; int i = 0; while (lFirst <= lLast && rFirst <= rLast) { // 两个子数组都不为空,比较数组头 if (array[lFirst] <= array[rFirst]) { // 左子数组头小于右子数组,表头不存在逆序 temp[i] = array[lFirst]; i++; lFirst++; } else { // 左子数组头大于右子数组头,说明左子数组中所有元素都大于右子数组头,所以一共有左子数组 // 个数的逆序对,resultCount += lLast - lFirst + 1 resultCount = resultCount + lLast - lFirst + 1; if(resultCount>1000000007)//数值过大求余 { resultCount%=1000000007; } temp[i] = array[rFirst]; i++; rFirst++; } } // 右子数组空 while (lFirst <= lLast) { temp[i++] = array[lFirst++]; } // 左子数组空 while (rFirst <= rLast) { temp[i++] = array[rFirst++]; } // 将辅助数组中的元素交给原数组 for (int num = 0; num < i; num++) { //主要用于排序的 array[first + num] = temp[num]; } } }
相关文章推荐
- javascript-计算24
- [树状数组] poj 1990 MooFest
- JSON转换包含Date日期属性的对象的List集合报错问题
- css 居中总结
- js 的 深拷贝 和 浅拷贝
- JavaScript - 基于原型的面向对象
- 认识Servlet
- JSTL的配置与使用
- css样式重置
- [php学习十二]javaScript的基本练习3-Dom
- css中具有继承性的属性
- JQuery学习之旅(5)
- Populating Next Right Pointers in Each Node
- My Html
- Js制作移动漂浮广告
- H5成长之路 元素及文本对齐方式
- CSS3中各标签、id、class等名称须与相应html文件中一一对应
- Fedora20下vim的安装过程
- HTML5 Video标签的属性、方法和事件汇总介绍
- JS自学|常用互动方法