-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesign hashset.java
132 lines (108 loc) · 2.83 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
Explore
Problems
Interview
Contest
Discuss
Store
🔈 LeetCode is hiring! Apply NOW.🔈
Premium
11
104
Description
Solution
Discuss (999+)
Submissions
Back
Simple Java implementation | Rehashing | load Factor | 80% faster
6
abhi9720's avatar
abhi9720
609
Last Edit: 3 hours ago
219 VIEWS
For loop on list is almost negligible as if load factor goes greater than 0.7, Set Will Rehash
class MyHashSet {
ArrayList<ArrayList<Integer>> set;
int bucketSize ;
int size;
public MyHashSet() {
bucketSize = 10;
size = 0;
set = new ArrayList<>();
for(int i=0;i<bucketSize;i++){
set.add(null);
}
}
private int getBucketIndex(int key){
return key % bucketSize;
}
private double loadFactor(){
return 1.0*size/bucketSize;
}
private void rehash(){ // rehash is expensive
ArrayList<ArrayList<Integer>> temp = set;
set = new ArrayList<>();
bucketSize*=1.5;
for(int i=0;i<bucketSize;i++){
set.add(null);
}
size = 0;
for(int i=0;i<temp.size();i++ ){
ArrayList<Integer> li = temp.get(i);
if(li!=null){
for(int ele :li){
add(ele);
}
}
}
}
public void add(int key) {
double load = loadFactor();
if(load > 0.7){
rehash();
}
int index = getBucketIndex(key);
ArrayList<Integer> li = set.get(index);
if(li==null){
li = new ArrayList<>();
set.set( index, li );
}
for(int i=0;i<li.size();i++ ){
if(li.get(i)==key ){
return;
}
}
size++;
li.add(key);
}
public void remove(int key) {
int index = getBucketIndex(key);
ArrayList<Integer> li = set.get(index);
if(li==null) return;
int idx = -1;
for(int i=0;i<li.size();i++ ){
if(li.get(i)==key ){
idx = i;
break;
}
}
if(idx==-1) return;
int lastIndex = li.size()-1;
li.set(idx , li.get(lastIndex) ); // O(1) removal
li.remove(lastIndex);
size--;
}
public boolean contains(int key) {
int index = getBucketIndex(key);
ArrayList<Integer> li = set.get(index);
if(li==null){
return false;
}
for(int i=0;i<li.size();i++ ){
if(li.get(i)==key ){
return true;
}
}
return false;
}
}