-
Notifications
You must be signed in to change notification settings - Fork 2
/
170.py
120 lines (99 loc) · 3.53 KB
/
170.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# [ LeetCode ] 170. Two Sum III - Data structure design
def solution(operators: list[tuple[str, int]]) -> list[bool | None]:
class TwoSum:
def __init__(self) -> None:
self.numbers: list[int] = []
def add(self, number: int) -> None:
self.numbers.append(number)
def find(self, value: int) -> bool:
self.numbers.sort()
left, right = 0, len(self.numbers) - 1
while left < right:
target: int = self.numbers[left] + self.numbers[right]
if target == value:
return True
elif target > value:
right -= 1
else:
left += 1
return False
answer: list[bool | None] = []
for operator, number in operators:
if operator == "TwoSum":
cls: TwoSum = TwoSum()
answer.append(None)
elif operator == "add":
result = cls.add(number)
answer.append(result)
else:
result = cls.find(number)
answer.append(result)
return answer
def another_solution(operators: list[tuple[str, int]]) -> list[bool | None]:
class TwoSum:
def __init__(self) -> None:
self.numbers: dict[int, int] = {}
def add(self, number: int) -> None:
if number in self.numbers:
self.numbers[number] += 1
else:
self.numbers[number] = 1
def find(self, value: int) -> bool:
for number in self.numbers.keys():
target: int = value - number
if (
target in self.numbers
and
(target != number or self.numbers[target] > 1)
):
return True
return False
answer: list[bool | None] = []
for operator, number in operators:
if operator == "TwoSum":
cls: TwoSum = TwoSum()
answer.append(None)
elif operator == "add":
result = cls.add(number)
answer.append(result)
else:
result = cls.find(number)
answer.append(result)
return answer
if __name__ == "__main__":
cases: list[
dict[str, dict[str, list[tuple[str, int]]] | list[bool | None]]
] = [
{
"input": {
"operators": [
("TwoSum", None), ("add", 1), ("add", 3), ("add", 5),
("find", 4), ("find", 7)
]
},
"output": [None, None, None, None, True, False]
},
{
"input": {
"operators": [
("TwoSum", None), ("add", 0), ("find", 0)
]
},
"output": [None, None, False]
},
{
"input": {
"operators": [
("TwoSum", None), ("add", 0), ("add", 0), ("find", 0)
]
},
"output": [None, None, None, True]
},
]
for case in cases:
assert case["output"] == solution(
operators=case["input"]["operators"]
)
assert case["output"] == another_solution(
operators=case["input"]["operators"]
)