在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
O(nlogn)
归并排序的思想
比如 5 7
4 6
5>4 那么比5大的数也会大于4
所以 cnt += m - i + 1
java:
1 public class Solution { 2 private long cnt = 0 ; 3 private int[] tmp ; 4 public int InversePairs(int [] array) { 5 tmp = new int[array.length] ; 6 mergeSort(array , 0 , array.length - 1) ; 7 return (int)(cnt % 1000000007) ; 8 } 9 10 private void mergeSort(int [] array , int left , int right){ 11 if (right - left < 1) 12 return ; 13 int mid = left + (right - left) / 2 ; 14 mergeSort(array , left , mid) ; 15 mergeSort(array , mid + 1 , right) ; 16 merge(array , left , mid , right) ; 17 } 18 19 private void merge(int [] array , int left , int m , int right){ 20 int i = left , j = m+1 , k = left ; 21 while(i <= m || j <= right){ 22 if (i > m){ 23 tmp[k++] = array[j++] ; 24 }else if(j > right){ 25 tmp[k++] = array[i++] ; 26 }else if(array[i] < array[j]){ 27 tmp[k++] = array[i++] ; 28 }else{ 29 tmp[k++] = array[j++] ; 30 cnt += m - i + 1 ; // a[i] > a[j],说明 a[i...mid] 都大于 a[j] 31 } 32 } 33 for(k = left ; k <= right ; k++){ 34 array[k] = tmp[k] ; 35 } 36 } 37 }
C++:
vector<int>& data
1 class Solution { 2 private: 3 long cnt = 0 ; 4 vector<int> temp ; 5 public: 6 int InversePairs(vector<int> data) { 7 temp.resize(data.size()) ; 8 mergeSort(data , 0 , data.size() - 1) ; 9 return (int)(cnt%1000000007) ; 10 } 11 12 void mergeSort(vector<int>& data , int left , int right){ 13 if (right - left < 1){ 14 return ; 15 } 16 int mid = left + (right - left) / 2 ; 17 mergeSort(data , left , mid) ; 18 mergeSort(data , mid+1 , right) ; 19 merge(data , left , mid , right) ; 20 } 21 22 void merge(vector<int>& data , int left ,int mid , int right){ 23 int i = left ; 24 int j = mid+1 ; 25 int k = left ; 26 while(i <= mid || j <= right){ 27 if (i > mid){ 28 temp[k++] = data[j++] ; 29 }else if (j > right){ 30 temp[k++] = data[i++] ; 31 }else if (data[i] < data[j]){ 32 temp[k++] = data[i++] ; 33 }else{ 34 temp[k++] = data[j++] ; 35 cnt += mid-i+1 ; 36 } 37 } 38 for(i = left ; i <= right ; i++){ 39 data[i] = temp[i] ; 40 } 41 } 42 };