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)

 

posted on 2019-04-11 09:49  锋上磬音  阅读(98)  评论(0编辑  收藏  举报