-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDesignHashSet.java
More file actions
56 lines (45 loc) · 1.75 KB
/
Copy pathDesignHashSet.java
File metadata and controls
56 lines (45 loc) · 1.75 KB
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
// 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.
// See: https://leetcode.com/problems/design-hashset/
package leetcode.design;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class DesignHashSet {
class MyHashSet {
private List<List<Integer>> table;
private int capacity = 16;
private int size = 0;
public MyHashSet() {
table = new ArrayList<List<Integer>>(capacity);
for (int i = 0; i < capacity; i++)
table.add(new LinkedList<>());
}
public void add(int key) {
table.get(key % capacity).add(key);
size++;
if ((float) size / capacity >= 0.75) {
capacity *= 2;
List<List<Integer>> newTable = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++)
newTable.add(new LinkedList<>());
for (List<Integer> list : table)
for (Integer element : list)
newTable.get(element % capacity).add(element);
table = newTable;
}
}
public void remove(int key) {
table.get(key % capacity).removeIf(e -> e == key);
size--;
}
public boolean contains(int key) {
return table.get(key % capacity).contains(key);
}
}
public static void main(String[] args) {
}
}