-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-hashset.java
38 lines (33 loc) · 1.18 KB
/
design-hashset.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class MyHashSet {
boolean[] arr = new boolean[100];// start with 100 elements for fast initialization
/** Initialize your data structure here. */
public MyHashSet() {
}
public void add(int key) {
if(key>=arr.length) // if array is too small to accomodate key, extend it.
extend(key);
arr[key]=true;
}
public void remove(int key) {
if(key>=arr.length) // if array is too small to accomodate key, extend it.
extend(key);
arr[key]=false;
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
if(key>=arr.length) // key cannot be in array if array's length < key
return false;
return arr[key];//==true;
}
public void extend(int key){
arr= Arrays.copyOf(arr, key+1); // extend array to one more item than necessary, we need "key" items.
// we give "key+1" items to reduce collisions.
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
* obj.remove(key);
* boolean param_3 = obj.contains(key);
*/