剑指offer——数组中的逆序对C++(75%)

剑指offer——数组中的逆序对C++(75%)_第1张图片
非常好的题,利用了归并排序的特性。

#include
class Solution {
     
public:
    //cop[left...mid]是有序的,cop[mid+1...right]是有序的
    /*int mergeAndCount(vector& cop, int left, int mid, int right, vector& 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;
    }
    
};

你可能感兴趣的:(剑指Offer,#,排序算法,数据结构,算法,归并排序,剑指offer)