-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
detect-squares.py
70 lines (56 loc) · 1.8 KB
/
detect-squares.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Time: ctor: O(1)
# add: O(1)
# count: O(n)
# Space: O(n)
import collections
class DetectSquares(object):
def __init__(self):
self.__x_to_ys = collections.defaultdict(set)
self.__point_counts = collections.defaultdict(int)
def add(self, point):
"""
:type point: List[int]
:rtype: None
"""
self.__x_to_ys[point[0]].add(point[1])
self.__point_counts[tuple(point)] += 1
def count(self, point):
"""
:type point: List[int]
:rtype: int
"""
result = 0
for y in self.__x_to_ys[point[0]]:
if y == point[1]:
continue
dy = y-point[1]
result += self.__point_counts[(point[0], y)]*self.__point_counts[(point[0]+dy, point[1])]*self.__point_counts[(point[0]+dy, y)]
result += self.__point_counts[(point[0], y)]*self.__point_counts[(point[0]-dy, point[1])]*self.__point_counts[(point[0]-dy, y)]
return result
# Time: ctor: O(1)
# add: O(1)
# count: O(n)
# Space: O(n)
import collections
class DetectSquares2(object):
def __init__(self):
self.__points = []
self.__point_counts = collections.defaultdict(int)
def add(self, point):
"""
:type point: List[int]
:rtype: None
"""
self.__points.append(point)
self.__point_counts[tuple(point)] += 1
def count(self, point):
"""
:type point: List[int]
:rtype: int
"""
result = 0
for x, y in self.__points:
if not (point[0] != x and point[1] != y and (abs(point[0]-x) == abs(point[1]-y))):
continue
result += self.__point_counts[(point[0], y)]*self.__point_counts[(x, point[1])]
return result