LeetCode 705 Design HashSet 解题报告

自定义HashSet实现
本文介绍了一个不使用内置哈希表库的HashSet实现方法,包括添加、查找和删除元素的功能。通过Python代码示例,详细解释了如何利用集合的特性完成这些操作。

题目要求

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值