Reverse Pairs
For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.
Example
Given A = [2, 4, 1, 3, 5]
, (2, 1), (4, 1), (4, 3)
are reverse pairs. return 3
利用mergesort 达到nlogn的复杂度
1 public class Solution { 2 /** 3 * @param A an array 4 * @return total of reverse pairs 5 */ 6 int count = 0; 7 int[] helper; 8 public long reversePairs(int[] A) { 9 // Write your code here 10 if(A == null || A.length == 0) return 0; 11 helper = new int[A.length]; 12 mergeCount(A, 0, A.length-1); 13 return count; 14 } 15 16 private void mergeCount(int[] A, int low, int high) { 17 if (low==high) { 18 return; 19 } 20 int mid = (low+high)/2; 21 mergeCount(A, low, mid); 22 mergeCount(A, mid+1, high); 23 merge(A, low, mid, high); 24 } 25 26 private void merge(int[] A, int low, int mid, int high){ 27 for(int i=low; i<=high; i++){ 28 helper[i] = A[i]; 29 } 30 int i=low; 31 int j= mid+1; 32 int k=low; 33 34 while(i<=mid&&j<=high){ 35 if(helper[i]>helper[j]){ 36 A[k] = helper[j]; 37 j++; 38 count += (mid-i+1); 39 }else{ 40 A[k] = helper[i]; 41 i++; 42 } 43 k++; 44 } 45 while(i<=mid){ 46 A[k++] = helper[i++]; 47 } 48 } 49 }