LEEDCODE 170 交易逆序对的总数

LEEDCODE 170 交易逆序对的总数_第1张图片

class Solution {
public:
    int reversePairs(vector<int>& record) {
        int count = 0;
        int mid = record.size() / 2;
        int left = 0;
        int right = record.size() - 1;
        // int count_left = merge_sort(left, mid, record);
        // int count_right = merge_sort(mid+1, right, record);
        int count_merge = merge_sort(left, right, record);
        // count = count_left + count_right + count_merge;
        return count_merge;
    }
    int merge_sort(int left, int right, vector<int>& record)
    { 
        
        if(left >= right)
        {
            return 0;
        }
        int mid = left + (right - left) / 2;
        int cl = merge_sort(left, mid, record);
        int cr = merge_sort(mid+1, right, record);
        int cm = merge(left, right, record);
        int c = (cm + cl + cr);
        return c;
    }
    int merge(int left, int right, vector<int>& record)
    {
        int mid = left + (right - left) / 2;
        int i = left;
        int j = mid + 1;
        vector<int> a;
        int cnt = 0;
        while(i <= mid && j <= right)
        {
            if(record[i] <= record[j])
            {
                a.push_back(record[i]);
                i += 1;
            }
            else
            {
                a.push_back(record[j]);
                cnt += (mid - i +1);
                j += 1;
            }
        }
        if(i <= mid  && j > right)
        {
            while( i <= mid)
            {
                a.push_back(record[i]);
                i += 1;
            }
        }
        if(j <= right && i > mid)
        {
            while( j <= right)
            {
                a.push_back(record[j]);
                j += 1;
            }
        }
        int k = 0;
        for(int i = left; i <= right; i++)
        {
            record[i] = a[k++];
        }
        return cnt;
    }

};

LEEDCODE 170 交易逆序对的总数_第2张图片
Thinking:
1 在暴力解法(双层for)上思考 。LEEDCODE 170 交易逆序对的总数_第3张图片

(7 要和6 2 3 4 1比 )
归并方法

  • 分区间 7和6比、和2 3 比、和4 1 8比

归并排序,合并:左右区间是有序的 。以右区间每一个元素为遍历的focus, 和左区间都会比一遍 这时的合并正好与逆序对计数对应

你可能感兴趣的:(算法,c++)