劍指offer——陣列中的逆序對C++(75%)

baixiaofei567發表於2020-12-30

在這裡插入圖片描述
非常好的題,利用了歸併排序的特性。

#include<vector>
class Solution {
public:
    //cop[left...mid]是有序的,cop[mid+1...right]是有序的
    /*int mergeAndCount(vector<int>& cop, int left, int mid, int right, vector<int>& fuzhu){
        //先全放入輔助陣列中,然後按序放回原始陣列,在放回去的時候計算逆序對個數
        for(int i = left; i <= right; ++i){
            fuzhu[i] = cop[i];
        }
        int i = left, j = mid+1;
        int cnt = 0;//後面的先被放回去,證明cnt要++了,這是一對逆序對
        for(int k = left; k <= right; k++){
            //此題明確說明沒有相同的數字,所以不一定要加=
            //如果沒有說明,一定要加,因為左邊的優先被放進去,確保穩定性
            if(i == mid+1){
                cop[k] = fuzhu[j];
                j++;
            }
            else if(j == right+1){
                cop[k] = fuzhu[i];
                i++;
            }
            else if(fuzhu[i] <= fuzhu[j]){
                cop[k] = fuzhu[i];
                i++;
            }
            else{
                cop[k] = fuzhu[j];
                cnt += (mid-i+1);
                j++;
            }
        }
        return cnt%1000000007;
    }*/
    
    int mergeAndCount(vector<int>& cop, int left, int right,vector<int>& fuzhu){
        //遞迴邊界,當l=r,證明只有一個元素,就是有序的,返回0
        if(left == right) return 0;
        //函式進行到這一步至少有兩個數字
        int mid = left + (right-left)/2;
        //傳入的都是閉區間,這兩步時為了拆分陣列
        int lcnt = mergeAndCount(cop,left,mid,fuzhu)%1000000007;
        int rcnt = mergeAndCount(cop,mid+1,right,fuzhu)%1000000007;
        
        int cnt = 0;
        int i = left, j = mid+1;
        //先把資料傳入輔助陣列,然後將排好序的陣列傳回原陣列(cop)
        
        for(int i = left; i<= right; ++i){
            fuzhu[i] = cop[i];
        }
        
        for(int k = left; k <= right; ++k){
            if(i == mid+1){
                cop[k] = fuzhu[j++];
            }
            else if(j==right+1){
                cop[k] = fuzhu[i++];
            }
            else if(fuzhu[i] <= fuzhu[j]){
                cop[k] = fuzhu[i++];
            }
            else{
                cop[k] = fuzhu[j++];
                cnt += (mid-i+1);
            }
        }
        return (lcnt+rcnt+cnt%1000000007)%1000000007;
    }
    
    int InversePairs(vector<int> data) {
        if(data.size() < 2) return 0;
        
        //看看是否可以在原陣列上更改,如果不行就建立一個copy陣列存放data,
        vector<int> cop(data.size());
        for(int i = 0; i < data.size(); ++i){
            cop[i] = data[i];
        }
        vector<int> fuzhu(data.size());
        return mergeAndCount(cop,0,data.size()-1,fuzhu)%1000000007;
    }
    
};

相關文章