Detect Squares
求设计一个数据结构,里面有add,添加一个点, 和count,算有多少个可以用这个点和其他的点围成的正方形.
因为是正方形, 所以边长都一样, 而且题目要求是以轴为基准的正方形, 所以只需要判断有多少个正方形是同y和同x, 即可.
class DetectSquares {
int[][] g = new int[1001][1001];
public DetectSquares() {
}
public void add(int[] point) {
g[point[0]][point[1]]++;
}
public int count(int[] point) {
int res = 0;
for(int i = 0; i < 1001; i++){
if(Math.abs(point[0] - i) > 0){
int j1 = point[1] + Math.abs(point[0] - i);
if(0 <= j1 && j1 <= 1000){
res += g[i][j1] * g[i][point[1]] * g[point[0]][j1];
}
int j2 = point[1] - Math.abs(point[0] - i);
if(0 <= j2 && j2 <= 1000){
res += g[i][j2] * g[i][point[1]] * g[point[0]][j2];
}
}
}
return res;
}
}
/**
* Your DetectSquares object will be instantiated and called as such:
* DetectSquares obj = new DetectSquares();
* obj.add(point);
* int param_2 = obj.count(point);
*/