美文网首页Leetcode
Leetcode 705. Design HashSet

Leetcode 705. Design HashSet

作者: SnailTyan | 来源:发表于2021-02-24 08:56 被阅读0次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Design HashSet

2. Solution

  • Version 1
class MyHashSet:

    def __init__(self):
        self.hashset  = []


    def add(self, key: int) -> None:
        if key not in self.hashset:
            self.hashset.append(key)


    def remove(self, key: int) -> None:
        if key in self.hashset:
            self.hashset.remove(key)


    def contains(self, key: int) -> bool:
        if key in self.hashset:
            return True
        return False
  • Version 2
class MyHashSet:
    def __init__(self):
        self.hashset  = [False] * 1000001


    def add(self, key: int) -> None:
        self.hashset[key] = True


    def remove(self, key: int) -> None:
        self.hashset[key] = False


    def contains(self, key: int) -> bool:
        return self.hashset[key]
  • Version 3
class MyHashSet:

    def __init__(self):
        self.hashset  = [[] for _ in range(1000)] 


    def add(self, key: int) -> None:
        index = self.hash(key)
        if key not in self.hashset[index]:
            self.hashset[index].append(key)


    def remove(self, key: int) -> None:
        index = self.hash(key)
        if key in self.hashset[index]:
            self.hashset[index].remove(key)


    def contains(self, key: int) -> bool:
        index = self.hash(key)
        return key in self.hashset[index]


    def hash(self, key):
        return key % 1000

Reference

  1. https://leetcode.com/problems/design-hashset/

相关文章

网友评论

    本文标题:Leetcode 705. Design HashSet

    本文链接:https://www.haomeiwen.com/subject/glmjfltx.html