-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathMyHashSet.java
85 lines (68 loc) · 1.86 KB
/
MyHashSet.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class MyHashSet {
boolean[] set = null;
/** Initialize your data structure here. */
public MyHashSet() {
set = new boolean[1000001];
}
public void add(int key) {
set[key] = true;
}
public void remove(int key) {
set[key] = false;
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
return set[key];
}
}
class MyHashSet {
// Hashset => 4(1), 10(2), 16(1) , 17(3)
/*
Hash
1 -> 4 -> 16 ->.... Time complexity => o(n)
2 -> 10 -> ...
3 -> 17 -> ...
*/
/** Initialize your data structure here. */
private int capacity = 0;
private List<Integer>[] set = null;
public MyHashSet() {
capacity = 1500;
set = new List[capacity];
}
private int getKeyHash(int key){
return key % capacity;
}
public void add(int key) {
int hashIndex = getKeyHash(key);
if(set[hashIndex] == null){
set[hashIndex] = new LinkedList<>();
}
if(set[hashIndex].indexOf(key) == -1){
set[hashIndex].add(key);
}
}
public void remove(int key) {
if(contains(key)) {
int hashIndex = getKeyHash(key);
// removing the key from the set
set[hashIndex].remove(set[hashIndex].indexOf(key));
}
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
int hashIndex = getKeyHash(key);
if(set[hashIndex] == null || set[hashIndex].indexOf(key) == -1){
return false;
} else {
return true;
}
}
}
/**
* 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);
*/