数组中的逆序对(归并排序思路)
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
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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; } }
相关文章推荐
- 数组中的逆序对(归并排序)
- [洛谷P1908] 逆序对|归并排序|树状数组
- 归并排序求数组逆序对
- poj 2299 Ultra-QuickSort 【线段树 or 线段树+lazy or 树状数组 or 归并排序】 求逆序对
- 剑指offer之面试题36:数组中的逆序对-归并排序的应用
- 九度OJ 1348 数组中的逆序对 -- 归并排序
- 归并排序-数组中的逆序对
- 九度OJ 1348 数组中的逆序对 -- 归并排序
- DC-6:数组逆序的两种思路
- 剑指offer---数组中的逆序对(归并排序)PHP
- 【归并排序求逆序对个数】【树状数组求逆序对个数】
- 归并排序,树状数组 两种方法求逆序对
- 逆序对的两种算法【树状数组 / 归并排序】
- ?归并排序要看 数组的逆序对
- hiho一下 第三十九周 #1141 : 二分·归并排序之逆序对 【归并排序----树状数组】
- 剑指Offer 36题 数组中的逆序对 Java版 这个和归并排序一起看 对比差别在哪
- 归并排序求数组中的逆序对
- Ultra-QuickSort---poj2299 (归并排序.逆序数.树状数组.离散化)
- 求逆序对模板题(完善模板:树状数组或归并排序)
- 【算法】逆序对问题的四种解法(归并排序,BST,树状数组,线段树)及变形