b_lc_检测正方形(先找对角点,然后判断另外两点)

设计一个算法:

  • 添加 一个在数据流中的新点到某个数据结构中。可以添加 重复 的点,并会视作不同的点进行处理。
  • 给你一个查询点,请你从数据结构中选出三个点,使这三个点和查询点一同构成一个 面积为正 的 轴对齐正方形 ,统计 满足该要求的方案数目。

轴对齐正方形 是一个正方形,除四条边长度相同外,还满足每条边都与 x-轴 或 y-轴 平行或垂直。

思路:枚举出所有add进去的对角的点,然后判断其余两个点是否在容器中

class DetectSquares {
public:
    map<pair<int, int>, int> cnt;

    DetectSquares() {

    }

    void add(vector<int> point) {
        cnt[{point[0], point[1]}]++;
    }

    int count(vector<int> point) {
        int ans = 0;
        int x = point[0], y = point[1];
        for (const auto &[p, c] : cnt) {
            int x1 = p.first, y1 = p.second;
            if (x == x1 || y == y1) {
                continue;
            }
            if (abs(x - x1) == abs(y - y1)) {
                ans += c * cnt[{x, y1}] * cnt[{x1, y}];
            }
        }
        return ans;
    }
};
posted @ 2021-09-19 19:13  童年の波鞋  阅读(56)  评论(0编辑  收藏  举报