Skip to content

Commit 14eb0b1

Browse files
committed
solution of Time Based Key-Value Store (based on hashmap and binary search)
1 parent 31b9941 commit 14eb0b1

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// https://leetcode.com/problems/time-based-key-value-store
2+
package main
3+
4+
type TimeMap struct {
5+
data map[string][]timeMapRecord
6+
}
7+
8+
type timeMapRecord struct {
9+
ts int
10+
val string
11+
}
12+
13+
/** Initialize your data structure here. */
14+
func Constructor() TimeMap {
15+
return TimeMap{
16+
data: make(map[string][]timeMapRecord),
17+
}
18+
}
19+
20+
func (this *TimeMap) Set(key string, value string, timestamp int) {
21+
d, ok := this.data[key]
22+
if !ok {
23+
d = make([]timeMapRecord, 0)
24+
}
25+
d = append(d, timeMapRecord{
26+
ts: timestamp,
27+
val: value,
28+
})
29+
this.data[key] = d
30+
}
31+
32+
func (this *TimeMap) Get(key string, timestamp int) string {
33+
d, ok := this.data[key]
34+
if !ok {
35+
return ""
36+
}
37+
// binary search
38+
l := 0
39+
r := len(d) - 1
40+
idx := -1
41+
for l <= r {
42+
m := (l + r) / 2
43+
if d[m].ts < timestamp {
44+
l = m + 1
45+
idx = m
46+
continue
47+
} else if d[m].ts > timestamp {
48+
r = r - 1
49+
} else {
50+
idx = m
51+
break
52+
}
53+
}
54+
if idx == -1 {
55+
return ""
56+
}
57+
return d[idx].val
58+
}
59+
60+
/**
61+
* Your TimeMap object will be instantiated and called as such:
62+
* obj := Constructor();
63+
* obj.Set(key,value,timestamp);
64+
* param_2 := obj.Get(key,timestamp);
65+
*/

0 commit comments

Comments
 (0)