-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathProblem2.cs
More file actions
95 lines (73 loc) · 2 KB
/
Problem2.cs
File metadata and controls
95 lines (73 loc) · 2 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
/*
I have implemented a hashmap using double hashing. By default, each bucket is allocated the value -1. If a key is not present, I return
-1 to the user. If key exists in the hashmap, the corresponding value is returned to the user if it's present, or -1 is returned.
*/
public class MyHashMap
{
private int[][] buckets;
private int bucketCount;
private int bucketSize;
public MyHashMap()
{
bucketCount = 1000;
bucketSize = 1000;
buckets = new int[bucketCount][];
}
public void Put(int key, int value)
{
int hash1 = HashFunction1(key);
if (buckets[hash1] == null)
{
if (hash1 == 0)
{
buckets[hash1] = new int[bucketSize + 1];
}
else
{
buckets[hash1] = new int[bucketSize];
}
Array.Fill(buckets[hash1], -1);
}
int hash2 = HashFunction2(key);
buckets[hash1][hash2] = value;
}
public int Get(int key)
{
int hash1 = HashFunction1(key);
if (buckets[hash1] == null)
{
return -1;
}
int hash2 = HashFunction2(key);
return buckets[hash1][hash2];
}
public void Remove(int key)
{
int hash1 = HashFunction1(key);
if (buckets[hash1] != null)
{
int hash2 = HashFunction2(key);
buckets[hash1][hash2] = -1;
}
}
private int HashFunction1(int key)
{
return key % bucketCount;
}
private int HashFunction2(int key)
{
return key / bucketSize;
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.Put(key,value);
* int param_2 = obj.Get(key);
* obj.Remove(key);
*/