版权声明:made by YYT https://blog.csdn.net/qq_37621506/article/details/83549771
1.题目
705:
不使用任何内建的哈希表库设计一个哈希集合
具体地说,你的设计应该包含以下的功能
add(value):向哈希集合中插入一个值。
contains(value) :返回哈希集合中是否存在这个值。
remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
706:
不使用任何内建的哈希表库设计一个哈希映射 具体地说,你的设计应该包含以下的功能 put(key,
value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。 remove(key):如果映射中存在这个键,删除这个数值对。
2.思路
705:
建立布尔类型向量,初始值均为false;
add:每加入一个数,对应值改为true;
706:
建立int类型向量,初始化值均为-1;
put:把对应数字改变
3.代码
class MyHashSet {
public:
/** Initialize your data structure here. */
MyHashSet() {
hashSet = vector<bool> (1000001, false);
}
void add(int key) {
hashSet[key] = true;
return ;
}
void remove(int key) {
if(hashSet[key]) {
hashSet[key] = false;
return ;
}
return ;
}
/** Returns true if this set did not already contain the specified element */
bool contains(int key) {
return hashSet[key];
}
private:
vector<bool> hashSet;
};
class MyHashMap {
public:
/** Initialize your data structure here. */
MyHashMap() {
HashMap = vector<int> (1000001, -1);
}
/** value will always be positive. */
void put(int key, int value) {
HashMap[key] = value;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int get(int key) {
return HashMap[key];
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
HashMap[key] = -1;
}
private:
vector<int> HashMap;
};