【问题标题】:Improving HashSet Design in Python [closed]改进 Python 中的 HashSet 设计 [关闭]
【发布时间】:2021-06-28 07:30:07
【问题描述】:

在这里学习!

我已经为 Leetcode 上的一个问题整理了这个解决方案! 以下是此解决方案的统计信息: 运行时间:1236 毫秒,比 Python3 在线提交的 Design HashSet 快 17.28% 内存使用:18.7 MB,不到 Python3 在线提交 Design HashSet 的 83.53%。

现在 - 我希望 Leetcode 能够展示一个理想或最佳实践的解决方案,以便我可以与我的比较和学习!但他们没有!

所以,如果你们中的任何人可以在这里,将不胜感激! (批评并展示您的最佳实践解决方案)

我的解决方案

class MyHashSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.TheSet = []
        

    def add(self, key: int) -> None:
        if self.contains(key):
            pass
        else:
            if key >= 0 and key <= 10**6:
                self.TheSet.append(key)
            else:
                pass

    def remove(self, key: int) -> None:
        if self.contains(key):
            self.TheSet.remove(key)
        else:
            pass

    def contains(self, key: int) -> bool:
        if key in self.TheSet:
            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)```

【问题讨论】:

  • 您介意分享挑战的链接吗?您的代码不像名称所暗示的那样使用哈希。也许,这可以改善您的解决方案。
  • 请编辑您问题中的图片,使其为文本,因此代码为minimal reproducible example,包括作为文本的数据
  • “这是我的代码,它可以工作,但也许可以改进,请批评”不是一个适合 Stack Overflow 的问题 - 应该在codereview.stackexchange.com 提问
  • 因为您实际上并没有实现哈希集...您只是在使用列表...哈希集的全部意义在于它们比用于检查成员资格的列表更好

标签: python hashset


【解决方案1】:

我找到了挑战并玩了一点。我想问题是你没有使用 HashSet 的基本概念,这将在你在 LeetCode 上尝试的挑战中解释。这里还有一个question,他们解释了 HashMap 的作用。会去看看!

我还根据这个answer为你做了一个解决方案。它的运行时间优于 80%,内存使用率优于 90%。显然,这可以进一步改进,但我认为它包含基本概念。

class MyHashSet:

    def __init__(self):
        self.contents = [None] * 1_000
        
    def hash(self, x):
        return x % (2 ** 61 - 1)
    
    def add(self, key:int) -> None:
        key_hash = self.hash(key) % 1_000
        bucket = self.contents[key_hash]
        
        if bucket is None:
            self.contents[key_hash] = [key]
        elif key not in bucket:
            bucket.append(key)
        return None

    def remove(self, key: int) -> None:
        key_hash = self.hash(key) % 1_000
        bucket = self.contents[key_hash]
        
        if bucket is not None:
            if key in bucket:
                bucket.remove(key)
        else:
            pass
        
    def contains(self, key: int) -> bool:
        key_hash = self.hash(key) % 1_000
        bucket = self.contents[key_hash]
        
        if bucket is not None:
            if key in bucket:
                return True
            else:
                return False
        else:
            return False

【讨论】:

  • 初始不需要保留None;只是让列表为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 2023-03-07
相关资源
最近更新 更多