【劍指offer】數組中的逆序對,C++實現


原創博文,轉載請注明出處!
本題牛客網地址

博客文章索引地址

博客文章中代碼的github地址

1.題目

image

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> &copy, 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 };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM