题目链接:2013. 检测正方形
如题,用几个哈希表分别记录 x 相同的点和 y 相同的点,以及每个点的数目即可。
from collections import defaultdict
from itertools import product
from typing import List
class DetectSquares:
def __init__(self):
self.points = defaultdict(int) # point -> count
self.x_lookup = defaultdict(set)
self.y_lookup = defaultdict(set)
def add(self, point: List[int]) -> None:
x, y = point
self.points[(x, y)] += 1
self.x_lookup[x].add(y)
self.y_lookup[y].add(x)
def count(self, point: List[int]) -> int:
px, py = point
if len(self.points) < 3 or len(self.x_lookup[px]) == 0 or len(self.y_lookup[py]) == 0:
return 0
return sum(
self.points[(px + dx, py)] * self.points[(px, py + dy)] * self.points[(px + dx, py + dy)] for dx, dy in
product((x - px for x in self.y_lookup[py]), (y - py for y in self.x_lookup[px])) if dx == dy != 0)
# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)