数组中的逆序对(归并排序思路)
来源:互联网 发布:seo新手教程 编辑:程序博客网 时间:2024/06/06 03:37
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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[n]; 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; }}
阅读全文
0 0
- 数组中的逆序对(归并排序思路)
- 数组中的逆序对(归并排序)
- 归并排序求数组中的逆序对
- 归并排序-数组中的逆序对
- 数组中的逆序对(归并排序)
- 数组中的逆序对(归并排序+剑指offer)
- 数组中的逆序对(归并排序思想解题)
- 归并排序及延伸(找出数组中的逆序对)
- 九度OJ 1348 数组中的逆序对 -- 归并排序
- 利用归并排序思想求数组中的逆序对
- 归并排序 & 数组中的逆序对 【java实现】
- 数组中的逆序对:归并排序的变形。
- 归并排序思想应用之----求数组中的逆序对
- 剑指Offer--数组中的逆序对--归并排序!
- 利用归并排序求数组中的逆序对
- 九度OJ 1348:数组中的逆序对 (排序、归并排序)
- 数组中的逆序对——分治法(归并排序的应用)
- 剑指offer——数组中的逆序对(复习归并排序)
- ajax和json
- 学习笔记25-前缀/中缀/后缀表达式
- h5测试点
- Xamarin.Forms——上传图片
- 解题报告:HDU_6185 Covering (轮廓线DP+高斯消元+矩阵快速幂)
- 数组中的逆序对(归并排序思路)
- HDU 1087 FatMouse and Cheese——DP
- jdbc利用集合传递参数
- bitset总结
- MySQL 聚簇索引和非聚簇索引
- 深入理解Java虚拟机(第二章):Java内存区域与内存溢出异常
- Java_基础—多线程之间的通信以及JDK1.5新特性互斥锁
- git基本命令
- 初识static静态