File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ class MyHashSet {
2
+ private final int SIZE = 100000 ;
3
+ private List <Integer > bucket [];
4
+ /** Initialize your data structure here. */
5
+ public MyHashSet () {
6
+ bucket = new List [SIZE ];
7
+ }
8
+
9
+ private int hash (int key ){
10
+ return key % SIZE ;
11
+ }
12
+
13
+ private int getPos (int key , int index ){
14
+ List <Integer > list = bucket [index ];
15
+ if (list == null ) return -1 ;
16
+ for (int i = 0 ; i < list .size (); i ++){
17
+ if (list .get (i ) == key )
18
+ return i ;
19
+ }
20
+ return -1 ;
21
+ }
22
+
23
+ public void add (int key ) {
24
+ int y = hash (key );
25
+ int pos = getPos (key , y );
26
+ if (pos < 0 ) {
27
+ if (bucket [y ] == null )
28
+ bucket [y ] = new ArrayList <Integer >();
29
+ bucket [y ].add (key );
30
+ }
31
+
32
+ }
33
+
34
+ public void remove (int key ) {
35
+ int y = hash (key );
36
+ int pos = getPos (key , y );
37
+ if (pos < 0 ) return ;
38
+ else {
39
+ bucket [y ].remove (pos );
40
+ }
41
+ }
42
+
43
+ /** Returns true if this set contains the specified element */
44
+ public boolean contains (int key ) {
45
+ int y = hash (key );
46
+ int pos = getPos (key , y );
47
+ if (pos < 0 ) return false ;
48
+ else return true ;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Your MyHashSet object will be instantiated and called as such:
54
+ * MyHashSet obj = new MyHashSet();
55
+ * obj.add(key);
56
+ * obj.remove(key);
57
+ * boolean param_3 = obj.contains(key);
58
+ */
You can’t perform that action at this time.
0 commit comments