设计哈希集合
参考做法
class MyHashSet {
static const int SIZE = 1997;
vector<vector<int>> table = vector<vector<int>>(SIZE);
public:
/** Initialize your data structure here. */
MyHashSet() {
}
void add(int key) {
auto &v = table[key % SIZE];
for(auto i: v){
if(i == key){
return;
}
}
v.push_back(key);
}
void remove(int key) {
auto &v = table[key % SIZE];
int i = 0;
int vSize = v.size();
for(i = 0; i < vSize; i++){
if(v[i] == key){
break;
}
}
if(i == vSize){
return;
}
int j = i;
i++;
while(i < vSize){
v[j++] = v[i++];
}
if(!v.empty()){
v.pop_back();
}
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
auto &v = table[key % SIZE];
for(auto i: v){
if(i == key){
return true;
}
}
return false;
}
};
/**
* 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);
*/
设计哈希映射
参考做法
class MyHashMap {
public:
/** Initialize your data structure here. */
int a[100000];
int b[100000]={0};
MyHashMap() {
}
/** value will always be non-negative. */
void put(int key, int value) {
a[key]=value;
b[key]=1;
}
/** 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) {
if(b[key]==0)return -1;
else return a[key];
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
if(b[key]==1){
a[key]=0;
b[key]=0;
}
}
};
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap* obj = new MyHashMap();
* obj->put(key,value);
* int param_2 = obj->get(key);
* obj->remove(key);
*/