检测正方形
难度:简单
对于 add 操作,我们可以使用「哈希表 套 哈希表」的方式,以 {x, {y : 点 (x,y) 的数量}} 的形式对传入点进行存储。
对于 count 查询而言,假定传入的点为 (x, y),我们可以先查询 x 行都有哪些列,枚举这些列( 即枚举点 (x, ny) ),由 y 和 ny 可得正方形边长 lenlen,此时再检查唯一确定的两点 (x±len,y) 和 (x±len,ny) 的出现次数,应用乘法原理,即可知道该正方形的方案数,统计所有合法方案数即是该询问的答案。
代码如下:
class DetectSquares {
Map<Integer, Map<Integer, Integer>> map = new HashMap<Integer, Map<Integer, Integer>>();
public DetectSquares() {
}
public void add(int[] point) {
int x = point[0];
int y = point[1];
Map<Integer, Integer> col2Cnt = map.getOrDefault(x, new HashMap<>());
col2Cnt.put(y,col2Cnt.getOrDefault(y,0)+1);
map.put(x,col2Cnt);
}
public int count(int[] point) {
int x = point[0];
int y = point[1];
Map<Integer, Integer> col2Cnt = map.getOrDefault(x,new HashMap<>());
int res = 0;
//x 相等,即两点之间形成的直线与y轴平行
for (Integer ny : col2Cnt.keySet()){
if (ny==y) continue;
int dif = ny - y;
if (map.containsKey(x+dif)) {
if (map.get(x+dif).containsKey(y) && map.get(x+dif).containsKey(ny)){
res += col2Cnt.get(ny) * map.get(x+dif).get(y) * map.get(x+dif).get(ny);
}
}
if (map.containsKey(x-dif)) {
if (map.get(x-dif).containsKey(y) && map.get(x-dif).containsKey(ny)){
res += col2Cnt.get(ny) * map.get(x-dif).get(y) * map.get(x-dif).get(ny);
}
}
}
return res;
}
}
执行结果:成功