原創博文,轉載請注明出處!
本題牛客網地址
1.題目
2.思路
3.代碼
1 class Solution { 2 public: 3 int InversePairs(vector<int> data) { 4 if(data.size() == 0){ 5 return 0; 6 } 7 // 排序的輔助數組 8 vector<int> copy; 9 for(int i = 0; i < data.size(); ++i){ 10 copy.push_back(data[i]); 11 } 12 return InversePairsCore(data, copy, 0, data.size() - 1) % 1000000007; 13 } 14 long InversePairsCore(vector<int> &data, vector<int> ©, int begin, int end){ 15 // 如果指向相同位置,則沒有逆序對。 16 if(begin == end){ 17 copy[begin] = data[end]; 18 return 0; 19 } 20 // 求中點 21 int mid = (end + begin) >> 1; 22 // 使data左半段有序,並返回左半段逆序對的數目 23 long leftCount = InversePairsCore(copy, data, begin, mid); 24 // 使data右半段有序,並返回右半段逆序對的數目 25 long rightCount = InversePairsCore(copy, data, mid + 1, end); 26 27 int i = mid; // i初始化為前半段最后一個數字的下標 28 int j = end; // j初始化為后半段最后一個數字的下標 29 int indexcopy = end; // 輔助數組復制的數組的最后一個數字的下標 30 long count = 0; // 計數,逆序對的個數,注意類型 31 32 while(i >= begin && j >= mid + 1){ 33 if(data[i] > data[j]){ 34 copy[indexcopy--] = data[i--]; 35 count += j - mid; 36 } 37 else{ 38 copy[indexcopy--] = data[j--]; 39 } 40 } 41 for(;i >= begin; --i){ 42 copy[indexcopy--] = data[i]; 43 } 44 for(;j >= mid + 1; --j){ 45 copy[indexcopy--] = data[j]; 46 } 47 return leftCount + rightCount + count; 48 } 49 };