Design and implement a TwoSum class. It should support the following operations: add
and find
.
add
- Add the number to an internal data structure.
find
- Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5); find(4) -> true find(7) -> false
class TwoSum(object):
def __init__(self):
"""
initialize your data structure here
"""
def add(self, number):
"""
Add the number to an internal data structure.
:rtype: nothing
"""
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
# Your TwoSum object will be instantiated and called as such:
# twoSum = TwoSum()
# twoSum.add(number)
# twoSum.find(value)
题目如上。根据题意,就是构建一个数据结构,能够完成add添加数字,find找到two sum。
我的思路是,因为有find,所以直接上来就觉得应该用hashtable之类的构建。对于python,练习下来觉得就是字典dictionary最好。
add没什么好说的,key有就+1,没有就添加。
<span style="white-space:pre"> </span>if number not in dic:
dic[number] = 1
else:
dic[number] += 1
对于find,因为是two sum,给了我们一个target值,那么就target - dic[i], 判断结果是不是在dic中,在就是True,否则就是False。
Target - dic[i] == dic[j]
考虑到可能有重复的数字,除了上面的情况,还有重复数字的情况。
Target - dic[i] == dic[i]
所以,合并一下,就是数字相同的时候,判断是否key数字的value大于1。不同的时候,就判断是否剩余值也在key中。
value - num in dic and (value - num != num or dic[num] > 1):
class TwoSum(object):
def __init__(self):
self.dic = {}
def add(self, number):
if number not in self.dic:
self.dic[number] = 1
else:
self.dic[number] += 1
def find(self, value):
dic = self.dic
for num in dic:
if value - num in dic and (value - num != num or dic[num] > 1):
return True
return False