给你一个在 X-Y 平面上的点构成的数据流。设计一个满足下述要求的算法:

添加 一个在数据流中的新点到某个数据结构中。可以添加 重复 的点,并会视作不同的点进行处理。 给你一个查询点,请你从数据结构中选出三个点,使这三个点和查询点一同构成一个 面积为正 的 轴对齐正方形 ,统计 满足该要求的方案数目。 轴对齐正方形 是一个正方形,除四条边长度相同外,还满足每条边都与 x-轴 或 y-轴 平行或垂直。

实现 DetectSquares 类:

DetectSquares() 使用空数据结构初始化对象 void add(int[] point) 向数据结构添加一个新的点 point = [x, y] int count(int[] point) 统计按上述方式与点 point = [x, y] 共同构造 轴对齐正方形 的方案数。  

示例: alt

输入: ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] 输出: [null, null, null, null, 1, 0, null, 2]

解释: DetectSquares detectSquares = new DetectSquares(); detectSquares.add([3, 10]); detectSquares.add([11, 2]); detectSquares.add([3, 2]); detectSquares.count([11, 10]); // 返回 1 。你可以选择: // - 第一个,第二个,和第三个点 detectSquares.count([14, 8]); // 返回 0 。查询点无法与数据结构中的这些点构成正方形。 detectSquares.add([11, 2]); // 允许添加重复的点。 detectSquares.count([11, 10]); // 返回 2 。你可以选择: // - 第一个,第二个,和第三个点 // - 第一个,第三个,和第四个点  

提示:

point.length == 2 0 <= x, y <= 1000 调用 add 和 count 的 总次数 最多为 5000

题解: 可以使用哈希表统计表出现的次数,用数组记录下非重复的点,将点和查询点计算斜率,如果斜率不为1,则跳过,对角线的点确定后,正方形也随之确定,故可以统计点出现的次数。

class DetectSquares {
public:
    vector<vector<int>> points;
    map<vector<int>, int> m;
    DetectSquares() {
        points.clear();
        m.clear();
    }
    
    void add(vector<int> point) {
        if(!m[point]){
            points.push_back(point);
            m[point]++;
        }
        else{
            m[point]++;
        }
    }
    
    int count(vector<int> point) {
        int ans = 0;
        for(auto p: points){
            if(p[0] == point[0]) continue;
            if(p[1] == point[1]) continue;
            double k = (p[1] - point[1]) * 1.0 / (p[0] - point[0]);
            if(abs(k) != 1) continue;
            int tmp = m[p];
            //cout<<"p:"<<p[0]<<" "<<p[1]<<" point:"<<point[0]<<" "<<point[1]<<" tmp:"<<tmp<<endl;
            //cout<<"m[p]:"<<m[p]<<" m[point]:"<<m[point]<<endl;
            vector<int> pairs1(2);
            vector<int> pairs2(2);
            pairs1[0] = p[0], pairs1[1] = point[1];
            pairs2[0] = point[0], pairs2[1] = p[1];
            
            tmp = tmp * m[pairs1] * m[pairs2];
            ans += tmp;
        }
        return ans;
    }
};

/**
 * Your DetectSquares object will be instantiated and called as such:
 * DetectSquares* obj = new DetectSquares();
 * obj->add(point);
 * int param_2 = obj->count(point);
 */