-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path705.design-hash-set.java
64 lines (56 loc) · 1.51 KB
/
705.design-hash-set.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
/*
* @lc app=leetcode id=705 lang=java
*
* [705] Design HashSet
*/
// @lc code=start
/*
取base = 997(prime number), 建立bucket数组, 每个bucket对应一个linkedList(remove时间是O(1))
如果遇到collision, 添加元素到对应list末尾
time: O(n) n:size of the linkedlist
*/
class MyHashSet {
List<Integer>[] buckets;
int base = 997;
/** Initialize your data structure here. */
public MyHashSet() {
buckets = new LinkedList[base];
}
public void add(int key) {
int pos = hashing(key);
if (buckets[pos] == null) {
buckets[pos] = new LinkedList<>();
}
if (buckets[pos].indexOf(key) == -1) {
buckets[pos].add(key);
}
}
public void remove(int key) {
int pos = hashing(key);
if (buckets[pos] != null) {
int index = buckets[pos].indexOf(key);
if (index != -1) {
buckets[pos].remove(index);
}
}
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
int pos = hashing(key);
if (buckets[pos] != null) {
return buckets[pos].indexOf(key) != -1;
}
return false;
}
private int hashing(int num) {
return num % base;
}
}
/**
* 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);
*/
// @lc code=end