Skip to content

Leetcode 2857. Count Pairs of Points With Distance k #293

@Woodyiiiiiii

Description

@Woodyiiiiiii

2857. Count Pairs of Points With Distance k

2857. Count Pairs of Points With Distance k

观察到k的值域比较小,可以直接暴力枚举,然后根据异或关系和前缀数量,返回结果。

我这道题也一开始没想法。我一直从另一个坐标出发考虑,思考如何异或构成一个值,然后合起来为k。实际上需要反过来考虑,从最外层出发往内思考,既然k暗示了可以循环k,那就假设k的两个数,求坐标。

class Solution {
    public int countPairs(List<List<Integer>> coordinates, int k) {
        Map<List<Integer>, Integer> map = new HashMap<>();
        int ans = 0;
        for (List<Integer> coordinate : coordinates) {
            int x = coordinate.get(0), y = coordinate.get(1);
            for (int k1 = 0; k1 <= k; k1 ++) {
                int x1 = k1 ^ x, y1 = (k - k1) ^ y;
                ans += map.getOrDefault(Arrays.asList(x1, y1), 0);
            }
            map.merge(Arrays.asList(x, y), 1, Integer::sum);
        }
        return ans;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions