100213. 按距离统计房屋对数目 II

100213. 按距离统计房屋对数目 II - 力扣(LeetCode) 

class Solution {
public:
    vector<int> dif;
    void add(int l, int r, int d) {
        if (l > r) return;
        dif[l] += d;
        dif[r + 1] -= d;
        return;
    }
    vector<long long> countOfPairs(int n, int x, int y) {
        dif.resize(n + 5);
        if (x > y) swap(x, y);        
        for (int i = 1; i <= n; i++) {
            //add(1, i - 1, 1);
            add(1, n - i, 2);
            if (x + 1 >= y) continue;
            if (i <= x) {
                add(y - i, n - i, -2);
                add(x - i + 1, x - i + 1 + n - y, 2);
            }
            else if (i > x && i < (y + x - 2) / 2) {
                int j = (2 * i - x + 1 + y) / 2 + 1;
                add(j - i, y - 1 - i, -2);
                add(i - x + 2, i - x + 1 + y - j, 2);
            }
            else if (i > (y + x + 1) / 2 && i < y) {
                add(i - x, i - 1, -2);
                add(y - i + 1, y - i + x, 2);
            }
            else if (i >= y) {
                int j = (y + x - 1) / 2;
                add(i - j, i - x - 1, -2);
                add(i - y + 2, i - y + 1 + j - x, 2);
            }
        }
        vector<long long> ans(1, dif[1]);
        for (int i = 2; i <= n; i++) {
            ans.push_back(ans.back() + dif[i]);
        }
        return ans;
    }
};
class Solution {
public:
    vector<int> dif;
    void add(int l, int r) {
        dif[l]++, dif[r + 1]--;
        return;
    }
    vector<long long> countOfPairs(int n, int x, int y) {
        if (x > y) swap(x, y);
        vector<long long> ans;
        if (y - x < 2) {
            for (int i = 1; i <= n; i++) ans.push_back((n - i) * 2);
            return ans;
        }
        dif.resize(n + 5);
        for (int i = 1; i < n; i++) {
            if (i <= x) {
                int j = (y + x + 1) / 2 + 1;
                add(1, j - i - 1);
                add(x - i + 2, x - i + y - j + 1);
                add(x - i + 1, x - i + n - y + 1);
            }
            else if (i < (y + x) / 2) {
                int j = i + (y - x + 1) / 2;
                add(1, j - i);
                add(i - x + 2, i - x + y - j);
                add(i - x + 1, i - x + n - y + 1);
            }
            else add(1, n - i);
        }
        ans.push_back(2 * dif[1]);
        for (int i = 2; i <= n; i++) {
            ans.push_back(ans.back() + dif[i] * 2);
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云儿乱飘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值