剑指 Offer 51 数组中的逆序对

树状数组写法

class Solution {
     
public:
    #define maxn 50050
    #define lowbit(i) (i&(-i))
    int n, m, a[maxn], b[maxn], c[maxn];
    void update(int x){
     
        for(int i = x ; i <= m ; i += lowbit(i)) c[i] ++;
        return;
    }
    int query(int x){
     
        int ans = 0;
        for(int i = x ; i > 0 ; i -= lowbit(i)) ans += c[i];
        return ans;
    }
    int reversePairs(vector<int>& nums) {
     
        for(auto v : nums) a[++n] = v, b[n] = a[n];
        sort(b + 1, b + 1 + n);
        m = unique(b + 1, b + 1 + n) - b - 1;
        int ans = 0;
        for(int i = 1 ; i <= n ; ++ i){
     
            a[i] = lower_bound(b + 1, b + 1 + m, a[i]) - b;
            update(a[i]);
            ans += i - query(a[i]);
        }
        return ans;
    }
};

归并写法

class Solution {
     
public:
    #define maxn 50050
    int n, ans, a[maxn], b[maxn];
    void msort(int l, int r){
     
        if(l == r) return;
        int mid = (l + r) >> 1;
        if(l <= mid) msort(l, mid);
        if(r > mid) msort(mid + 1, r);
        int i = l, j = mid + 1, k = l;
        while(i <= mid && j <= r){
     
            if(a[i] <= a[j]) b[k++] = a[i++];
            if(a[i] > a[j]) b[k++] = a[j++], ans += mid - i + 1;
        }
        while(i <= mid) b[k++] = a[i++];
        while(j <= r) b[k++] = a[j++];
        for(int i = l ; i <= r ; ++ i) a[i] = b[i];
    }
    int reversePairs(vector<int>& nums) {
     
        for(auto v : nums) a[++n] = v;
        msort(1, n);
        return ans;
    }
};

你可能感兴趣的:(面试)