35數組中的逆序對

 

題目描述

在數組中的兩個數字,若是前面一個數字大於後面的數字,則這兩個數字組成一個逆序對。輸入一個數組,求出這個數組中的逆序對的總數P。並將P對1000000007取模的結果輸出。 即輸出P%1000000007c++

輸入描述:

題目保證輸入的數組中沒有的相同的數字
數據範圍:
對於%50的數據,size<=10^4
對於%75的數據,size<=10^5
對於%100的數據,size<=2*10^5

示例1
數組

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

 

輸出

7spa

思路:
相似於megersort

先統計子數組內部的逆序對的數目,而後再統計2個相鄰子數組之間的逆序對的數目,在統計的過程當中,還須要對數組排序,
排序能夠避免重複統計。
code

 1 public class Solution {
 2     public int InversePairs(int [] a) {  
 3         int[] aux = new int[a.length];
 4         for(int i = 0;i<a.length;i++)
 5             aux[i] = a[i];
 6         
 7         return fun(a,aux,0,a.length-1);
 8     }
 9     private int fun(int[] a,int[] aux,int lo,int hi){
10         if(lo==hi) return 0;
11         int mid = (hi-lo)/2+lo;
12         int left = fun(a,aux,lo,mid)%1000000007;
13         int right = fun(a,aux,mid+1,hi)%1000000007;
14         
15         int i = mid;
16         int j = hi;
17         int ai = hi;//aux_index
18         int  count = 0;
19         while(i>=lo&&j>=mid+1){
20             if(a[i]>a[j]){
21                 aux[ai--] = a[i--];
22                 count+=j-mid;
23                 if(count>=1000000007)//數值過大求餘
24                     count%=1000000007;       
25             }
26             else
27                 aux[ai--]=a[j--];
28         }
29         
30         while(i>=lo)
31             aux[ai--]=a[i--];
32         while(j>=mid+1)
33             aux[ai--] =a[j--];    
34         
35         //更新數組
36         for(int k = lo;k<=hi;k++)
37             a[k] = aux[k];
38         
39         return (left+right+count)%1000000007;
40     }
41 }

 

 

 

c++ 20180725blog

 

 1 class Solution {
 2 public:
 3     int InversePairs(vector<int> data) {
 4         int length = data.size();
 5         if(length<=0) return 0;
 6         std::vector<int> copy(data);
 7         long long cnt = InversePairsCore(data,copy,0,length-1);
 8         return cnt;
 9     }
10     long long InversePairsCore(std::vector<int> &data,std::vector<int> &copy,int lo,int hi){
11         if(lo==hi) return 0;
12         int mid = lo+(hi-lo)/2;
13         long long left = InversePairsCore(data,copy,lo,mid);
14         long long right  =InversePairsCore(data,copy,mid+1,hi);
15 
16         int i = mid;
17         int j = hi;
18         int k = hi;
19         int cnt = 0;
20         while(i>=lo&&j>=mid+1){
21             if(data[i]>data[j]){
22                 copy[k--]=data[i--];
23                 cnt+=j-mid;
24                 if(cnt>=1000000007)
25                 cnt%=1000000007;
26             }
27             else{
28                 copy[k--]=data[j--];
29             }
30         }
31         while(i>=lo)
32             copy[k--] = data[i--];
33         while(j>=mid+1)
34             copy[k--] = data[j--];
35         for(int m = lo;m<=hi;m++)
36             data[m]  =copy[m];
37         return (left+right+cnt)%1000000007;
38     }
39 };
相關文章
相關標籤/搜索