Leetcode2857. 统计距离为 k 的点对

Every day a Leetcode

题目来源:2857. 统计距离为 k 的点对

解法1:暴力

暴力枚举数组 coordinates 的两个点 coordinates[i] = (x1, y1) 和 coordinates[j] = (x2, y2),它们的距离 d = (x1 XOR x2) + (y1 XOR y2) ,XOR 指的是按位异或运算。

返回满足 i < j 且 d = k 的点对数目。

代码:

class Solution
{
public:
    int countPairs(vector<vector<int>> &coordinates, int k)
    {
        int n = coordinates.size();

        int count = 0;
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
            {
                int x1 = coordinates[i][0], y1 = coordinates[i][1];
                int x2 = coordinates[j][0], y2 = coordinates[j][1];
                int d = (x1 ^ x2) + (y1 ^ y2);
                if (d == k)
                    count++;
            }

        return count;
    }
};

结果:超时

复杂度分析:

时间复杂度:O(n2),其中 n 是数组 coordinates 的元素个数。

空间复杂度:O(1)。

解法2:哈希 + 暴力

在这里插入图片描述

代码:

// 哈希

class Solution
{
public:
    int countPairs(vector<vector<int>> &coordinates, int k)
    {
        int n = coordinates.size();
        unordered_map<long long, int> cnt;
        int count = 0;

        for (vector<int> &coordinate : coordinates)
        {
            int x = coordinate[0], y = coordinate[1];
            // 令 x1 ^ x2 = i,i 的范围为 [0, k]
            for (int i = 0; i <= k; i++)
            {
                // 把 (x, y) 压缩成一个整数,例如 1e6 * x + y
                auto iter = cnt.find(1000000LL * (x ^ i) + (y ^ (k - i)));
                if (iter != cnt.end())
                    count += iter->second;
            }
            cnt[1000000LL * x + y]++;
        }

        return count;
    }
};

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n * k),其中 n 是数组 coordinates 的元素个数。

空间复杂度:O(n),其中 n 是数组 coordinates 的元素个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

UestcXiye

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

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

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

打赏作者

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

抵扣说明:

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

余额充值