不使用任何內建的哈希表庫設計一個哈希集合(HashSet)。
實現 MyHashSet 類:
void add(key) 向哈希集合中插入值 key 。
bool contains(key) 返回哈希集合中是否存在這個值 key 。
void remove(key) 將給定值 key 從哈希集合中刪除。如果哈希集合中沒有這個值,什么也不做。
示例:
輸入:
[“MyHashSet”, “add”, “add”, “contains”, “contains”, “add”, “contains”, “remove”, “contains”]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
輸出:
[null, null, null, true, false, null, true, null, false]
解釋:
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // 返回 True
myHashSet.contains(3); // 返回 False ,(未找到)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // 返回 True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // 返回 False ,(已移除)
提示:
0 <= key <= 106
最多調用 104 次 add、remove 和 contains 。
解題思路
使用Boolean類型數組 hash【key】表示 key值是否存在
代碼
class MyHashSet {boolean[] hash;/** Initialize your data structure here. */public MyHashSet() {hash=new boolean[10000001];}public void add(int key) {hash[key]=true;}public void remove(int key) {hash[key]=false;}/** Returns true if this set contains the specified element */public boolean contains(int key) {return hash[key];}}/*** Your MyHashSet object will be instantiated and called as such:* MyHashSet obj = new MyHashSet();* obj.add(key);* obj.remove(key);* boolean param_3 = obj.contains(key);*/