Last active
April 24, 2024 21:53
-
-
Save hydev777/6bdb56d089f0245f830fb5d685db9ba5 to your computer and use it in GitHub Desktop.
HashSet in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomHashSet { | |
CustomHashSet(); | |
final _keys = List<List<int>>.generate(1000, (index) => []); | |
List<List<int>> get keys { | |
return _keys; | |
} | |
int _hashFunction(int key) { | |
return key % 1000; | |
} | |
void add(int key) { | |
int index = _hashFunction(key); | |
if (!contains(key)) { | |
_keys[index].add(key); | |
} | |
} | |
void remove(int key) { | |
int index = _hashFunction(key); | |
if (contains(key)) { | |
int indexToRemove = 0; | |
for (int value = 0; value < _keys[index].length; value++) { | |
if (_keys[index][value] == key) { | |
indexToRemove = value; | |
} | |
} | |
_keys[index].removeAt(indexToRemove); | |
} | |
} | |
bool contains(int key) { | |
int index = _hashFunction(key); | |
for (int value = 0; value < _keys[index].length; value++) { | |
if (_keys[index][value] == key) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment