Skip to content

705. Design HashSet

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

js
/**
 * Initialize your data structure here.
 */
var MyHashSet = function() {
  this.set = new Set()
}

/**
 * @param {number} key
 * @return {void}
 */
MyHashSet.prototype.add = function(key) {
  this.set.add(key)
}

/**
 * @param {number} key
 * @return {void}
 */
MyHashSet.prototype.remove = function(key) {
  this.set.delete(key)
}

/**
 * Returns true if this set contains the specified element
 * @param {number} key
 * @return {boolean}
 */
MyHashSet.prototype.contains = function(key) {
  return this.set.has(key)
}

/**
 * Your MyHashSet object will be instantiated and called as such:
 * var obj = Object.create(MyHashSet).createNew()
 * obj.add(key)
 * obj.remove(key)
 * var param_3 = obj.contains(key)
 */
py
class MyHashSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.set = set()

    def add(self, key):
        """
        :type key: int
        :rtype: void
        """
        self.set.add(key)

    def remove(self, key):
        """
        :type key: int
        :rtype: void
        """
        if key in self.set:
            self.set.remove(key)

    def contains(self, key):
        """
        Returns true if this set contains the specified element
        :type key: int
        :rtype: bool
        """
        return key in self.set


# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)