Leetcode-981. Time Based Key-Value Store 基于时间的键值存储 (二分法)-python

题目

创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作:
1.set(string key, string value, int timestamp)
-存储键 key、值 value,以及给定的时间戳 timestamp。
2.get(string key, int timestamp)
-返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp。
-如果有多个这样的值,则返回对应最大的 timestamp_prev 的那个值。
-如果没有值,则返回空字符串("")。
链接:https://leetcode.com/problems/time-based-key-value-store/

Create a timebased key-value store class TimeMap, that supports two operations.

  1. set(string key, string value, int timestamp)
  • Stores the key and value, along with the given timestamp.
  1. get(string key, int timestamp)
  • Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
  • If there are multiple such values, it returns the one with the largest timestamp_prev.
  • If there are no values, it returns the empty string ("").

Example:

Input: inputs = [“TimeMap”,“set”,“get”,“get”,“set”,“get”,“get”], inputs = [[],[“foo”,“bar”,1],[“foo”,1],[“foo”,3],[“foo”,“bar2”,4],[“foo”,4],[“foo”,5]]
Output: [null,null,“bar”,“bar”,null,“bar2”,“bar2”]
Explanation:
TimeMap kv;
kv.set(“foo”, “bar”, 1); // store the key “foo” and value “bar” along with timestamp = 1
kv.get(“foo”, 1); // output “bar”
kv.get(“foo”, 3); // output “bar” since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie “bar”
kv.set(“foo”, “bar2”, 4);
kv.get(“foo”, 4); // output “bar2”
kv.get(“foo”, 5); //output “bar2”

思路及代码

1.
  • 直接用传统的二分查找代码,但是只能pass 44/45,最后一个test case会超时
class TimeMap:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.kv = {}

    def set(self, key: str, value: str, timestamp: int) -> None:
        if key not in self.kv.keys():
            self.kv[key] = {timestamp: value}
        else:
            self.kv[key].update({timestamp:value})

    def get(self, key: str, timestamp: int) -> str:
        d = self.kv[key]
        d_key = sorted(d.keys())
        low = 0
        high = len(d_key)
        while low < high:
            mid = int((low+high) / 2)
            if d_key[mid] < timestamp:
                low = mid + 1
            elif d_key[mid] > timestamp:
                high = mid
            else:
                break
        if high - 1 < 0:
            return ""
        return d[d_key[high - 1]]


# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
2.
  • 发现所有的输入都是timestamp按照顺序排列好的,所以可以省略排序那一步
class TimeMap:
    def __init__(self):
        self.kv = defaultdict(list)
        
    def set(self, key: str, value: str, timestamp: int) -> None:
        self.kv[key].append([timestamp, value])

    def get(self, key: str, timestamp: int) -> str:
        d = self.kv[key]
        low = 0
        high = len(d)
        while low < high:
            mid = int((low+high) / 2)
            if d[mid][0] <= timestamp:
                low = mid + 1
            else:
                high = mid
        if high - 1 < 0:
            return ""
        else:
            return d[high-1][1]
3.
  • 利用字典查找复杂度为1,简化已经在dict中的timestamp查找的复杂度
  • 代码参考于leetcode-discuss
4. bisect
  • python中的数组二分查找算法bisect
  • 代码参考自leetcode-discuss
i = bisect.bisect(self.times[key], timestamp) # 返回high
return self.values[key][i - 1] if i else ''

你可能感兴趣的:(Leetcode,leetcode,python,二分法)