【leetcode】705. 设计哈希集合(design-hashset)(模拟)[简单]

链接

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

耗时

解题:11 min
题解:10 min

题意

不使用任何内建的哈希表库设计一个哈希集合(HashSet)。

实现 MyHashSet 类:

  • void add(key) 向哈希集合中插入值 key 。
  • bool contains(key) 返回哈希集合中是否存在这个值 key 。
  • void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。

提示:

  • 0 <= key <= 1 0 6 10^6 106
  • 最多调用 1 0 4 10^4 104 次 add、remove 和 contains 。

思路

用了一个线性哈希,而且因为知道 key 最大是 1 0 6 10^6 106,所以都不需要解决碰撞,直接开一个 1 0 6 10^6 106 的数组,数组全部初始化为 false,add() 就把数组下标为 key 的位置置为 true,remove() 就置为 false,contains() 就直接返回这个位置的值。

时间复杂度:add、remove 和 contains 均是 O ( 1 ) O(1) O(1)

AC代码

class MyHashSet {
    
    
private:
    vector<bool> hash_set;
public:
    /** Initialize your data structure here. */
    MyHashSet() {
    
    
        hash_set.resize(1000100, false);
    }
    
    void add(int key) {
    
    
        hash_set[key] = true;
    }
    
    void remove(int key) {
    
    
        hash_set[key] = false;
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
    
    
        return hash_set[key];
    }
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet* obj = new MyHashSet();
 * obj->add(key);
 * obj->remove(key);
 * bool param_3 = obj->contains(key);
 */

猜你喜欢

转载自blog.csdn.net/Krone_/article/details/114753999
今日推荐