2013.检测正方形
题目描述
思路
哈希表统计
先考虑如何实现int count(int[] point),记输入的point的横纵坐标分别为x和y。则形成的正方形的上下两条边中,其中一条边的纵坐标为y,枚举另一条边的纵坐标为col,则正方形的边长d为|y - col|且大于0。有了其中一个点的坐标(x, y)和一条横边的纵坐标col,即可知道正方形四个点的坐标分别为(x, y),(x, col),(x+d, y),(x+d, col)或(x, y),(x, col),(x-d, col),(x-d, y)。
因此可以用哈希表存储void add(int[] point)函数加入的点。先把点按照行来划分,键为行的纵坐标,值为另一个哈希表,其中键为该行中的点的横坐标,值为这样的点的个数。因为点会重复出现,所以计算正方形的个数时需要把另外三个坐标出现的次数相乘。
Python实现
class DetectSquares:
def __init__(self):
self.map = defaultdict(Counter)
def add(self, point: List[int]) -> None:
x, y = point
self.map[y][x] += 1
def count(self, point: List[int]) -> int:
res = 0
x, y = point
if not y in self.map:
return 0
yCnt = self.map[y]
for col, colCnt in self.map.items():
if col != y:
d = col - y
res += colCnt[x] * yCnt[x + d] * colCnt[x + d]
res += colCnt[x] * yCnt[x - d] * colCnt[x - d]
return res
# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)
Java实现
class DetectSquares {
Map<Integer, Map<Integer, Integer>> cnt;
public DetectSquares() {
cnt = new HashMap<Integer, Map<Integer, Integer>>();
}
public void add(int[] point) {
int x = point[0], y = point[1];
cnt.putIfAbsent(y, new HashMap<Integer, Integer>());
Map<Integer, Integer> yCnt = cnt.get(y);
yCnt.put(x, yCnt.getOrDefault(x, 0) + 1);
}
public int count(int[] point) {
int res = 0;
int x = point[0], y = point[1];
if (!cnt.containsKey(y)) {
return 0;
}
Map<Integer, Integer> yCnt = cnt.get(y);
Set<Map.Entry<Integer, Map<Integer, Integer>>> entries = cnt.entrySet();
for (Map.Entry<Integer, Map<Integer, Integer>> entry : entries) {
int col = entry.getKey();
Map<Integer, Integer> colCnt = entry.getValue();
if (col != y) {
// 根据对称性,这里可以不用取绝对值
int d = col - y;
res += colCnt.getOrDefault(x, 0) * yCnt.getOrDefault(x + d, 0) * colCnt.getOrDefault(x + d, 0);
res += colCnt.getOrDefault(x, 0) * yCnt.getOrDefault(x - d, 0) * colCnt.getOrDefault(x - d, 0);
}
}
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);
*/