解题思路:
首先分析一下题目,问题是要求输入一个坐标,判断在已有的坐标集合里,找出所有能构成平行于坐标轴的正方形的个数。那么显然,我们要记录每个坐标点的个数,可以用map<pair<int, int>, int>
来存储,但是在寻找的时候不能通过x坐标来找y坐标,所以还需要一个记录(x,y)对的数据结构,可以用map<int, set<int>>
来存储,这样也就固定了边的长度,输入坐标后,只要在(x,y)的哈希表中固定住x,一个个查看y是否符合要求并统计形成的正方形个数,代码如下:
class DetectSquares {
private:
map<pair<int, int>, int> mp;
// 记录相同x下不同的y
unordered_map<int, set<int>> xy;
public:
DetectSquares() {
}
void add(vector<int> point) {
xy[point[0]].insert(point[1]);
mp[{point[0], point[1]}] ++;
}
int count(vector<int> point) {
int ans = 0;
for(auto y : xy[point[0]]) {
if(y == point[1]) continue;
int len = y - point[1];
ans += mp[{point[0], point[1] + len}] * mp[{point[0] + len, point[1]}] * mp[{point[0] + len, point[1] + len}];
ans += mp[{point[0], point[1] + len}] * mp[{point[0] - len, point[1]}] * mp[{point[0] - len, point[1] + len}];
}
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);
*/