yankewei / LeetCode

LeetCode 问题的解决方法
MIT License
6 stars 0 forks source link

基于时间的键值存储 #138

Open yankewei opened 3 years ago

yankewei commented 3 years ago

创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作:

1. set(string key, string value, int timestamp)

2. get(string key, int timestamp)

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/time-based-key-value-store 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

yankewei commented 3 years ago

首先想到使用一个map来进行检索,然后就是可以使用一个切片来保存所以可能的值,但是要可以对这个值进行快速检索,自然就想要用二分查找。这里要注意sort.Search这个方法,它的结果是最小的符合匿名函数条件的索引

type pair struct {
    timestamp int
    value string
}

type TimeMap struct {
    m map[string][]pair
}

/** Initialize your data structure here. */
func Constructor() TimeMap {
    return TimeMap{m: map[string][]pair{}}
}

func (this *TimeMap) Set(key string, value string, timestamp int)  {
    this.m[key] = append(this.m[key], pair{timestamp: timestamp, value: value})
}

func (this *TimeMap) Get(key string, timestamp int) string {
    pairs := this.m[key]
    index := sort.Search(len(pairs), func(i int) bool { return pairs[i].timestamp > timestamp })

    if index > 0 {
    return pairs[index-1].value
    }
    return ""
}

/**
 * Your TimeMap object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Set(key,value,timestamp);
 * param_2 := obj.Get(key,timestamp);
 */