forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0706-design-hashmap.cs
97 lines (87 loc) · 2.1 KB
/
0706-design-hashmap.cs
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
96
97
public class MyHashMap
{
private class LinkedListNode
{
public LinkedListNode(int key, int val, LinkedListNode next)
{
this.Key = key;
this.Val = val;
this.Next = next;
}
public int Key { get; set; }
public int Val { get; set; }
public LinkedListNode Next { get; set; }
}
public MyHashMap()
{
Map = new LinkedListNode[10000];
}
public int Hash(int key)
{
return key % Map.Length;
}
public void Put(int key, int value)
{
int index = Hash(key);
if (Map[index] == null)
Map[index] = new LinkedListNode(key, value, null);
else
{
LinkedListNode node = Map[index];
while (true)
{
if (node.Key == key)
{
node.Val = value;
return;
}
if (node.Next == null)
break;
else
node = node.Next;
}
node.Next = new LinkedListNode(key, value, null);
}
}
public int Get(int key)
{
int index = Hash(key);
LinkedListNode node = Map[index];
if (node != null)
{
while (true)
{
if (node.Key == key)
return node.Val;
if (node.Next == null)
break;
else
node = node.Next;
}
}
return -1;
}
public void Remove(int key)
{
int index = Hash(key);
LinkedListNode node = Map[index];
if (node == null)
return;
if (node.Key == key)
{
Map[index] = node.Next;
node = null;
return;
}
while (node.Next != null)
{
if (node.Next.Key == key)
{
node.Next = node.Next.Next;
return;
}
node = node.Next;
}
}
private LinkedListNode[] Map { get; set; }
}