1. 题目
2. 思路
(1) 哈希表
- 利用哈希表存储点的坐标和个数、每条横轴上的点、每条竖轴上的点。
- 统计正方形个数时,外层遍历同一条横轴上的点,内层遍历同一条竖轴上的点,然后判断是否存在对角线点,若存在,则累加三点的个数乘积。
3. 代码
import java.util.*;
public class Test {
public static void main(String[] args) {
}
}
class DetectSquares {
private Map<Index, Integer> map;
private Map<Integer, List<Index>> mapX;
private Map<Integer, List<Index>> mapY;
public DetectSquares() {
map = new HashMap<>();
mapX = new HashMap<>();
mapY = new HashMap<>();
}
public void add(int[] point) {
Index index = new Index(point[0], point[1]);
if (map.containsKey(index)) {
map.put(index, map.get(index) + 1);
} else {
map.put(index, 1);
if (mapX.containsKey(index.x)) {
mapX.get(index.x).add(index);
} else {
List<Index> list = new ArrayList<>();
list.add(index);
mapX.put(index.x, list);
}
if (mapY.containsKey(index.y)) {
mapY.get(index.y).add(index);
} else {
List<Index> list = new ArrayList<>();
list.add(index);
mapY.put(index.y, list);
}
}
}
public int count(int[] point) {
int res = 0;
Index index = new Index(point[0], point[1]);
List<Index> listX = mapX.get(index.x);
List<Index> listY = mapY.get(index.y);
if (listX != null && listY != null) {
for (Index xIndex : listX) {
if (!xIndex.equals(index)) {
for (Index yIndex : listY) {
if (!yIndex.equals(index)) {
Index target = new Index(yIndex.x, xIndex.y);
if (Math.abs(target.x - index.x) == Math.abs(target.y - index.y) && map.containsKey(target)) {
res += map.get(xIndex) * map.get(yIndex) * map.get(target);
}
}
}
}
}
}
return res;
}
}
class Index {
public int x;
public int y;
public Index(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Index index = (Index) o;
return x == index.x && y == index.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Index{" +
"x=" + x +
", y=" + y +
'}';
}
}