天天看点

Leetcode 705. Design HashSet

文章作者:Tyan

博客:noahsnail.com | CSDN | 简书

1. Description

Leetcode 705. 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/