Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value)
: Insert a value into the HashSet.contains(value)
: Return whether the value exists in the HashSet or not.remove(value)
: Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
Example
add(1) : add(2) : contains(1): 1contains(1): 0add(1) :
Approach
Java
import java.util.Arrays;public class HashSetTest {public static void main(String[] args) {HashSetOwn set = new HashSetOwn();System.out.println("add(1) : ");set.add(1);System.out.println("add(2) : ");set.add(2);System.out.println("contains(1): " + set.contains(1));set.remove(1);System.out.println("contains(1): " + set.contains(1));System.out.println("add(1) : ");set.add(1);}}class HashSetOwn {int map[];public HashSetOwn() {map = new int[1000000];Arrays.fill(map, -1);}public void add(int key) {map[key] = 1;}public boolean contains(int key) {if (map[key] != -1)return true;return false;}public void remove(int key) {map[key] = -1;}}
C++
#include <bits/stdc++.h>using namespace std;class HashSetOwn {vector<int> map;public:HashSetOwn() {map.clear();map.resize(1000000,-1);}void add(int key) {map[key] =1;}bool contains(int key) {if (map[key] != -1)return true;return false;}void remove(int key) {map[key] = -1;}};int main(){HashSetOwn set;cout<<"add(1) : "<<"\n";set.add(1);cout<<"add(2) : "<<"\n";set.add(2);cout<<"contains(1): "<<set.contains(1)<<"\n";set.remove(1);cout<<"contains(1): "<<set.contains(1)<<"\n";cout<<"add(1) : "<<"\n";;set.add(1);return 0;}
No comments:
Post a Comment