forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSet.java
More file actions
52 lines (42 loc) · 1.59 KB
/
Copy pathHashSet.java
File metadata and controls
52 lines (42 loc) · 1.59 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
// Time Complexity :add,remove,contains->O(1);
// Space Complexity :O(n); where n is no of elements
// Did this code successfully run on Leetcode :yes
// Any problem you faced while coding this :tried to make array as int array then realised we can use boolean
class MyHashSet {
public int keyList = 1000;// taking keyList Size
public int keyItem = 1001;// taking nested array size as 1001 as item 1000000 will be on //index
// arr[0][1000]
boolean[][] hashSet = new boolean[keyList][];// initializing list
public MyHashSet() {
}
public void add(int key) {
int x = key % keyList;// calculating index using hash function
int y = key / keyList;
if (hashSet[x] == null) {
hashSet[x] = new boolean[keyItem];// initializing nested array
}
hashSet[x][y] = true;// setting value to true
}
public void remove(int key) {
int x = key % keyList;
int y = key / keyList;
if (hashSet[x] != null) {
hashSet[x][y] = false;// removing element by setting it to false at calculated //index
}
}
public boolean contains(int key) {
int x = key % keyList;
int y = key / keyList;
if (hashSet[x] != null) {
return hashSet[x][y];// if nested array is not null return its status
}
return false;// else it will automatically be false
}
}
/**
* 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);
*/