[牛客网]数组中的逆序对
来源:互联网 发布:单片机字节变量bdata 编辑:程序博客网 时间:2024/05/19 09:17
题目:
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
思路:输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
输入例子:
1,2,3,4,5,6,7,0
输出例子:
7
利用归并算法,在合并过程中统计逆序的个数
代码:
public class InversePair {/** * @param args */public int InversePairsCore(int [] array,int []a,int start,int end) { if(start==end) { a[start]=array[start]; return 0; } int len=(end-start)/2; int left=InversePairsCore(a,array,start,start+len)%1000000007; int right=InversePairsCore(a,array,start+len+1,end)%1000000007; int i=start+len; int j=end; int index=end; int count=0; while(i>=start&&j>=(start+len+1)) { if(array[i]>array[j]) { a[index--]=array[i--]; if(count>=1000000007) count=count%1000000007; count=count+j-start-len; } else a[index--]=array[j--]; } for(;i>=start;i--) a[index--]=array[i]; for(;j>=start+len+1;--j) a[index--]=array[j]; count=(count+left+right)%1000000007; return count; }public int InversePairs(int [] array) { if(array.length==0) return 0; int len=array.length; int a[]=new int[len]; for(int i=0;i<len;i++) a[i]=array[i]; int count=InversePairsCore(array,a,0,len-1); return count; }public static void main(String[] args) {// TODO Auto-generated method stubint []a={364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575};System.out.println(new InversePair().InversePairs(a));}}
阅读全文
0 0
- [牛客网]数组中的逆序对
- 牛客网 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- python--timeit模块
- Ember旅程系列(终章) -- 部署
- hadoop2.8.0的搭建
- javaWeb学习6.5
- python的学习 二维码的使用
- [牛客网]数组中的逆序对
- SSH HTTP HTTPS
- 日本传统色彩大全
- system()路径中含有 空格与 冒号及斜杠 ( \\与 “”)问题
- 浅谈二分查找
- java初学--读入输出
- Windows 7/8.1 下 双版本Python2.7/Python3.5 安装 GPU版的tensorflow
- RGB颜色查询对照表
- tensorflow深度学习原理