剑指offer—数组中的逆序对
来源:互联网 发布:java 格式化html 编辑:程序博客网 时间:2024/05/17 03:33
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
public class Solution { public int InversePairs(int [] array) { if(array==null || array.length<=0) return 0; int end = array.length-1; int[] copy = new int[array.length]; for(int i=0; i<array.length; i++){ copy[i] = array[i]; } int count = InversePairsCore(array,copy,0,end); return count; } public int InversePairsCore(int[] array, int[] copy,int start, int end){ if(start==end){ return 0; } int length = (end-start)/2; int left = InversePairsCore(copy,array,start,start+length)%1000000007; int right = InversePairsCore(copy,array,start+length+1,end)%1000000007; int i=start+length; int j = end; int index = end; int count = 0; while(i>=start && j>=start+length+1){ if(array[i]>array[j]){ count += (j-start-length); copy[index--] = array[i--]; if(count>=1000000007)//数值过大求余 { count%=1000000007; } }else{ copy[index--] = array[j--]; } } for(;i>=start;i--){ copy[index--] = array[i]; } for(; j>=start+length+1; j--){ copy[index--] = array[j]; } return (count+left+right)%1000000007; }}
利用归并排序的思想,先将数组分开,在合并,在两个小数组中合并之前,先计算每一个小数组的逆序对的个数,并分别讲每个小数组排序,在合并的过程中,从第一个小数组的最后一个元素出发,算出每个元素可以和后面数组有几个满足逆序对的
阅读全文
0 0
- 剑指offer—数组中的逆序对
- 剑指offer—数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer 36 数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指Offer之 - 数组中的逆序对
- 剑指offer之数组中的逆序对
- 剑指offer 36 - 数组中的逆序对
- 《剑指offer》数组中的逆序对
- 【剑指offer】数组中的逆序对
- 【剑指offer】之数组中的逆序对
- 剑指offer:数组中的逆序对
- [剑指offer]数组中的逆序对
- 剑指offer:数组中的逆序对
- 剑指Offer--036-数组中的逆序对
- [剑指offer]数组中的逆序对
- 《剑指offer》:[36]数组中的逆序对
- 《剑指offer》-数组中的逆序对
- 46、47-Permutations
- 最全centos源
- iPhone X 适配 ( iOS 11适配 ) 打理刘海
- Maven工具
- HTK语音识别中的决策树
- 剑指offer—数组中的逆序对
- 程序设计入门2 关于scanf()大彻大悟
- 收藏的
- Code Control MVC框架-创建一个Controller
- 真是企业级项目需求之--------防止SQL注入和XSS攻击Filter
- 表单语义化
- 趣图:实现这个功能啦,可以过一个安心的周……
- C++前序——(3)目标文件间的链接
- poj_1751_The Unique MST_prime输出部分路径