705. Design HashSet
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value)
: Insert a value into the HashSet.contains(value)
: Return whether the value exists in the HashSet or not.remove(value)
: Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
Example:
MyHashSet hashSet = new MyHashSet(); hashSet.add(1); hashSet.add(2); hashSet.contains(1); // returns true hashSet.contains(3); // returns false (not found) hashSet.add(2); hashSet.contains(2); // returns true hashSet.remove(2); hashSet.contains(2); // returns false (already removed)
Note:
- All values will be in the range of
[0, 1000000]
. - The number of operations will be in the range of
[1, 10000]
. - Please do not use the built-in HashSet library.
问题描述
在不使用任何内置哈希表库的情况下设计HashSet,实现添加,查找,移除等函数功能,哈希表长度为1000000.
解题思路
使用C++编程语言,利用vector容器创建哈希表,利用其内部函数实现哈希表的相关操作:
1.声明vector容器: vector<bool> HashSet;
2.对其初始化: HashSet=vector<bool>(1000001,false);
3.添加元素: HashSet[key]=true;
4.移除元素: HashSet[key]=false;
5.查看元素: return HashSet[key];
代码
static int pr=[]()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class MyHashSet {
private:
vector<bool>HashSet;
public:
/** Initialize your data structure here. */
MyHashSet() {
HashSet=vector<bool>(1000001,false);
}
void add(int key) {
HashSet[key]=true;
}
void remove(int key) {
HashSet[key]=false;
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
return HashSet[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);
*/
运行结果
总结
1.哈希表是一种数据结构,或者说是一种数据组织模型,哈希表结构的特点是一个关键字key对应一个值values,
通过关键字索引就能找到索引对应的值。哈希表我们可以用类似数组的结构来类比它,比如数组下标对应哈希表
的key,元素值对应哈希表的values.只是哈希表的key和values可以是任何数据类型。哈希表的结构思想就是根据
关键码值(Key value)来直接进行访问。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查
找的速度。
2.哈希表的难点在与如何解决哈希冲突,这道题目主要是让我们理解哈希表的概念,实现哈希表的初始化,添加,
移除,查找的功能,所以不用考虑的过于复杂。我们可以利用vector容器来构建哈希表,vector的元素类型可以任意,
我们使用bool型数据类型,便于表示该关键字的哈希值的所对应的哈希表的位置是否已经使用了,使用了true,反之false;
这样就能基本的表示哈希表通过关键字映射到表中的某个位置的概念。
3.该代码在C++中的目的是为了加快数据读取速度。我们知道C++的运行速度不如C的,那么主要的原因是C++的输入
输出流兼容了C的输入输出,因此,C++的速度才会变慢。下面代码可以去掉C++的输入输出的兼容性:
static int pr=[]()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
该代码下次详细解读,谢谢