-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution981.cs
57 lines (48 loc) · 1.48 KB
/
Solution981.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
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution981
{
/// <summary>
/// 981. Time Based Key-Value Store - Medium
/// <a href="https://leetcode.com/problems/time-based-key-value-store">See the problem</a>
/// </summary>
public class TimeMap
{
private readonly Dictionary<string, List<(int timestamp, string value)>> _map = [];
public void Set(string key, string value, int timestamp)
{
if (!_map.ContainsKey(key))
{
_map[key] = new List<(int timestamp, string value)>();
}
_map[key].Add((timestamp, value));
}
public string Get(string key, int timestamp)
{
if (!_map.ContainsKey(key))
{
return string.Empty;
}
var values = _map[key];
var left = 0;
var right = values.Count - 1;
while (left <= right)
{
var mid = left + (right - left) / 2;
if (values[mid].timestamp == timestamp)
{
return values[mid].value;
}
else if (values[mid].timestamp < timestamp)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return right >= 0 ? values[right].value : string.Empty;
}
}
}