标签:
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.
Given A = [2, 4, 1, 3, 5]
, (2, 1), (4, 1), (4, 3)
are reverse pairs. return 3
1 public class Solution { 2 /** 3 * @param A an array 4 * @return total of reverse pairs 5 */ 6 public long reversePairs(int[] A) { 7 if (A == null || A.length == 0) { 8 return 0; 9 } 10 int[] temp = new int[A.length]; 11 return mergeSort(A, temp, 0, A.length - 1); 12 } 13 14 private long mergeSort(int[] A, int[] temp, int left, int right) { 15 if (left >= right) { 16 return 0; 17 } 18 19 int sum = 0; 20 int mid = left + (right - left) / 2; 21 sum += mergeSort(A, temp, left, mid); 22 sum += mergeSort(A, temp, mid + 1, right); 23 sum += merge(A, temp, left, mid, right); 24 return sum; 25 } 26 27 private long merge(int[] A, int[] temp, int left, int mid, int right) { 28 int i = left, j = mid + 1; 29 int sum = 0; 30 for (int k = 0; k < right - left + 1; k++) { 31 if (i <= mid && (j > right || A[i] <= A[j])) { 32 temp[k] = A[i]; 33 i++; 34 } else { 35 temp[k] = A[j]; 36 if (i <= mid) { 37 sum += mid - i + 1; 38 } 39 j++; 40 } 41 } 42 for (int k = 0; k < right - left + 1; k++) { 43 A[left + k] = temp[k]; 44 } 45 return sum; 46 } 47 }
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5657442.html