1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public class Solution { int cnt; public int InversePairs(int [] array) { if(array.length != 0){ divide(array,0,array.length-1); } return cnt; } private void divide(int[] arr,int start,int end){ if(start >= end) return; int mid = start + (end - start)/2; divide(arr,start,mid); divide(arr,mid+1,end); merge(arr,start,mid,end); } private void merge(int[] arr,int start,int mid,int end){ int[] temp = new int[end-start+1]; int i=start,j=mid+1,k=0; while(i<=mid && j<=end){ if(arr[i] <= arr[j]){ temp[k++] = arr[i++]; }else{ temp[k++] = arr[j++]; cnt = (cnt+mid-i+1)%1000000007; } } while(i<=mid) temp[k++] = arr[i++]; while(j<=end) temp[k++] = arr[j++]; for (k = 0; k < temp.length; k++) arr[start + k] = temp[k]; } }
|