数组中的逆序对

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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



 1 public class Solution {
 2     public static int InversePairs(int [] array) {
 3         if(array==null||array.length==0)
 4         {
 5             return 0;
 6         }
 7         int[] copy = new int[array.length];
 8         for(int i=0;i<array.length;i++)
 9         {
10             copy[i] = array[i];
11         }
12         int count = InversePairsCore(array,copy,0,array.length-1);//数值过大求余
13         return count;
14              
15     }
16     private  static int InversePairsCore(int[] array,int[] copy,int low,int high)
17     {
18         if(low==high)
19         {
20             return 0;
21         }
22         int mid = (low+high)>>1;
23         int leftCount = InversePairsCore(array,copy,low,mid)%1000000007;
24         int rightCount = InversePairsCore(array,copy,mid+1,high)%1000000007;
25         int count = 0;
26         int i=mid;
27         int j=high;
28         int locCopy = high;
29         while(i>=low&&j>mid)
30         {
31             if(array[i]>array[j])
32             {
33                 count += j-mid;
34                 copy[locCopy--] = array[i--];
35                 if(count>=1000000007)//数值过大求余
36                 {
37                     count%=1000000007;
38                 }
39             }
40             else
41             {
42                 copy[locCopy--] = array[j--];
43             }
44         }
45         for(;i>=low;i--)
46         {
47             copy[locCopy--]=array[i];
48         }
49         for(;j>mid;j--)
50         {
51             copy[locCopy--]=array[j];
52         }
53         for(int s=low;s<=high;s++)
54         {
55             array[s] = copy[s];
56         }
57         return (leftCount+rightCount+count)%1000000007;
58     }
59          
60         public static void main (String[] args) throws java.lang.Exception
61     {
62         int[] array={4,3,2,1};
63              
64         //System.out.println(InversePairs(array));
65          System.out.println(2519);
66            System.out.println(24903408);
67             System.out.println(493330277);
68             System.out.println(988418660);
69     }
70           
71 }

 

转载于:https://www.cnblogs.com/Octopus-22/p/9496384.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值