https://leetcode-cn.com/problems/design-hashset/
Idée 1: Méthode d'adresse de chaîne sans prétention et ennuyeuse, par vecteur, avant _ vecteur de liste, avant \ _listv e c t o r , f o r w a r d _ l i s t (ce dernier est une seule liste chaînée).
class MyHashSet {
public:
/** Initialize your data structure here. */
const int num=2333;
vector<forward_list<int>> hashTable;
MyHashSet() {
hashTable.resize(num);
}
void add(int key) {
if(!contains(key))
hashTable[key%num].push_front(key);
}
void remove(int key) {
int idx=key%num;
forward_list<int>::iterator it=hashTable[idx].before_begin();
forward_list<int>::iterator nxt=hashTable[idx].begin();
forward_list<int>::iterator ed=hashTable[idx].end();
while(nxt!=ed&&*nxt!=key)
it=nxt++;
if(nxt!=ed)
hashTable[idx].erase_after(it);
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
int idx=key%num;
forward_list<int>::iterator it=hashTable[idx].begin();
forward_list<int>::iterator ed=hashTable[idx].end();
while(it!=ed&&*it!=key)
++it;
return it!=ed;
}
};
/**
* 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);
*/
Idée 2: L'arithmétique bit à bit implémente le hachage. Cette idée est assez intelligente. Pensez à utiliser un unsigned long long unsigned \ long \ longu n s i g n e d l o n g l o n g array réalise le hachage, peut aussi bien définir le module commebase de baseb a s e , puis pour n'importe quelletouche clék e y , nous pouvons le convertir en deux parties:⌊ clé / base ⌋ \ lfloor key / base \ rfloor⌊ k e y / b a s e ⌋和clé% clé de base \% basek e y % b a s e , la première partie détermine son indice dans le tableau, et la seconde partie détermine la représentation binaire de sa valeur à cet endroit (le code devrait être plus intuitif ici). Considérantull ullLa plage de valeurs du type u l l est[0, 2 64 - 1] [0,2 ^ {64} -1][ 0 ,26 4-1 ] , unull ullu l l type correspond à jusqu'à 64 valeurs, doncbase = 64 base = 64b a s e=6 4 , la plage du tableau doit être⌊ max _ key / base ⌋ + 1 \ lfloor max \ _key / base \ rfloor + 1⌊ m a x _ k e y / b a s e ⌋+1。
class MyHashSet {
public:
/** Initialize your data structure here. */
const int base=64;
vector<unsigned long long> hashTable;
MyHashSet() {
int max=1e6,num=max/base;
if(num*base==max)
++num;
hashTable.resize(num);
}
void add(int key) {
hashTable[key/base]|=1ull<<(key%base);
}
void remove(int key) {
hashTable[key/base]&=~(1ull<<(key%base));
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
return hashTable[key/base]&(1ull<<(key%base));
}
};
/**
* 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);
*/