您的位置:首页 > 其它

数组中的逆序对(归并排序思路)

2017-09-03 10:42 281 查看
题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

输入描述:

题目保证输入的数组中没有的相同的数字

数据范围:

对于%50的数据,size<=10^4

对于%75的数据,size<=10^5

对于%100的数据,size<=2*10^5

示例1

输入

1,2,3,4,5,6,7,0

输出

7

import java.util.*;

/**
* Created by kaizige on 2017/8/27.
*/

public class Main{

public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE>1000000007);
Scanner scan=new Scanner(System.in);
while(scan.hasNextInt()){
int n =scan.nextInt();
int[]arr=new int
;
for(int i=0;i<n;i++){
arr[i]=scan.nextInt();
}
int[]temp=Arrays.copyOf(arr,n);
long count =getCount(arr,temp,0,n-1);
System.out.println(count);
}
}
private static int getCount(int[]arr,int[]temp,int start,int end){
if(start==end){
temp[start]=arr[start];
return 0;
}
int mid=(start+end)/2;
int left=getCount(arr,temp,start,mid);
int right=getCount(arr,temp,mid+1,end);
int i=mid;
int j=end;
int index=end;
int count=0;
while(i>=start&&j>=mid+1){
if(arr[i]>arr[j]){
temp[index--]=arr[i--];
count+=j-mid;
if(count>=1000000007){//count过大求余数
count%=1000000007;
}
}else{
temp[index--]=arr[j--];
}
}
while(i>=start){
temp[index--]=arr[i--];
}
while(j>=mid+1){
temp[index--]=arr[j--];
}
for(int k=start;k<=end;k++){
arr[k]=temp[k];
}
return (left+right+count)%1000000007;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息