LeetCode 493. Reverse Pairs

题目

求数组中满足 i < j and nums[i] > 2*nums[j]的对数。

题解

先把所有的数及其两倍的树重排序一下,然后再用树状数组来统计。

int sum[100010];
int N = 100010;
class Solution {
public:


    inline int lowbit(int x) {
        return x & (-x);
    }

    void updata(int x, int val) {
        while (x <= N) {
            sum[x] += val;
            x += lowbit(x);
        }
    }

    int getsum(int x) {
        int ans = 0;
        while (x > 0) {
            ans += sum[x];
            x -= lowbit(x);
        }
        return ans;
    }

    int reversePairs(vector<int>& nums) {
        reverse(nums.begin(), nums.end());
        int ans = 0;
        long long tempNum[100010], cnt = 0;
        for (int i = 0; i < nums.size(); i++) {
            tempNum[cnt++] = nums[i];
            tempNum[cnt++] = nums[i] * 2LL;
        }
        sort(tempNum, tempNum + cnt);
        map<long long, int> mp;
        mp[tempNum[0]] = 1;
        int pre = 2;
        for (int i = 1; i < cnt; i++) {
            if (tempNum[i] == tempNum[i - 1]) {
                continue;
            }
            mp[tempNum[i]] = pre++;
        }
        memset(sum, 0, sizeof(sum));
        for (int i = 0; i < nums.size(); i++) {
            ans += getsum(mp[nums[i]] - 1);
            updata(mp[nums[i] * 2LL], 1);
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode)