Leetcode 705. Design HashSet

2021-03-02 16:31:09 浏览数 (1)

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

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞