Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bacb63a

Browse files
LC#705 implement hashset from scratch
1 parent b288f98 commit bacb63a

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package LinkedList;
2+
3+
import java.util.LinkedList;
4+
5+
public class DesignHashSet705 {
6+
7+
private int size;
8+
private LinkedList<Integer>[] bucketarray;
9+
private static final int DEFAULT_CAPACITY = 10;
10+
11+
public DesignHashSet705() {
12+
initbucket(DEFAULT_CAPACITY);
13+
size = 0;
14+
}
15+
16+
private void initbucket(int capacity) {
17+
bucketarray = new LinkedList[capacity];
18+
for (int i = 0; i < bucketarray.length; i++) {
19+
bucketarray[i] = new LinkedList<Integer>();
20+
}
21+
}
22+
23+
public void add(int key) {
24+
int bucketlocation = hashFunction(key);
25+
int datalocation = getDataWithinBucket(bucketlocation, key);
26+
27+
if (datalocation == -1) {
28+
// data was not present in bucket so let's add in hashset
29+
bucketarray[bucketlocation].add(key);
30+
size++;
31+
}
32+
33+
double lambda = size * 1.0 / bucketarray.length;
34+
if (lambda > 0.75)
35+
rehash();
36+
}
37+
38+
private int hashFunction(Integer key) {
39+
int index = key.hashCode();
40+
return Math.abs(index) % bucketarray.length;
41+
}
42+
43+
private int getDataWithinBucket(int location, int key) {
44+
LinkedList<Integer> currentBucket = bucketarray[location];
45+
int index = 0;
46+
for (Integer data : currentBucket) {
47+
if (data == key)
48+
return index;
49+
index++;
50+
}
51+
return -1; // if not found
52+
}
53+
54+
private void rehash() {
55+
LinkedList<Integer>[] oldbucket = bucketarray;
56+
initbucket(oldbucket.length * 2);
57+
size = 0;
58+
59+
for (int i = 0; i < oldbucket.length; i++) {
60+
for (Integer value : oldbucket[i]) {
61+
add(value); // call add method of our hashset
62+
}
63+
}
64+
}
65+
66+
public void remove(int key) {
67+
int bucketlocation = hashFunction(key);
68+
int datalocation = getDataWithinBucket(bucketlocation, key);
69+
70+
if (datalocation == -1)
71+
return; // if no data found
72+
else {
73+
bucketarray[bucketlocation].remove(datalocation);
74+
size--;
75+
}
76+
}
77+
78+
public boolean contains(int key) {
79+
int bucketlocation = hashFunction(key);
80+
int datalocation = getDataWithinBucket(bucketlocation, key);
81+
82+
if (datalocation == -1)
83+
return false;
84+
else
85+
return true;
86+
}
87+
}

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /