LeetCode 705 Design HashSet 解题报告
題目要求
Design a HashSet?without using any built-in hash table libraries.
To be specific, your design should include these functions:
- add(value):?Insert a value into the HashSet.?
- contains(value)?: Return whether the value exists in the HashSet or not.
- remove(value): Remove a value in?the HashSet. If the value does not exist in the HashSet, do nothing.
題目分析及思路
要求設計一個HashSet(不能使用任何內置庫),需要包含以下三個功能:
1)add(value):往HashSet中插入一個值
2)contains(value):判斷一個值是否存在在HashSet中,若在則返回True,否則返回False
3)remove(value):從HashSet中移除一個值,若HashSet中不存在該值,則什么也不用做
可以在初始化中添加一個空集合,利用集合的特性完成插入和刪除操作。
python代碼
class MyHashSet:
? ? def __init__(self):
? ? ? ? """
? ? ? ? Initialize your data structure here.
? ? ? ? """
? ? ? ? self.s = set()
? ? ? ??
? ? def add(self, key: int) -> None:
? ? ? ? self.s.add(key)
? ? ? ??
? ? def remove(self, key: int) -> None:
? ? ? ? if key in self.s:
? ? ? ? ? ? self.s.remove(key)
? ? ? ??
? ? def contains(self, key: int) -> bool:
? ? ? ? """
? ? ? ? Returns true if this set contains the specified element
? ? ? ? """
? ? ? ? if key in self.s:
? ? ? ? ? ? return True
? ? ? ? else:
? ? ? ? ? ? return False
? ? ? ? ? ??
? ? ? ??
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
?
轉載于:https://www.cnblogs.com/yao1996/p/10687783.html
總結
以上是生活随笔為你收集整理的LeetCode 705 Design HashSet 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 恐怖漫画电脑壁纸图片(电脑壁纸鬼怪)
- 下一篇: 怎么查电脑显示器评测结果(如何测试电脑显