Leetcode Daily Problem
705. Design HashSet
Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key)Inserts the valuekeyinto the HashSet.bool contains(key)Returns whether the valuekeyexists in the HashSet or not.void remove(key)Removes the valuekeyin the HashSet. Ifkeydoes not exist in the HashSet, do nothing.
In this question we have to design a set data structure, this set can be designed using different data strucrtures but we will design it using vector.
class MyHashSet {
public:
vector<int> v;
MyHashSet()
{
}
void add(int key)
{
bool flag=false;
for(int i=0;i<v.size();i++)
{
if(v[i]==key)
{
flag=true;
}
}
if(!flag)
{
v.push_back(key);
}
}
void remove(int key)
{
vector<int> :: iterator it;
it=v.begin();
for(int i=0;i<v.size();i++)
{
if(v[i]==key)
{
v.erase(it+i);
}
}
}
bool contains(int key)
{
bool flag=false;
for(int x:v)
{
if(x==key)
{
flag=true;
}
}
return flag;
}
};
