Open Zheaoli opened 1 year ago
/*
* @lc app=leetcode id=981 lang=typescript
*
* [981] Time Based Key-Value Store
*/
// @lc code=start
class TimeMap {
store = {} as { [index: string]: [string, number][] }
constructor() {
}
set(key: string, value: string, timestamp: number): void {
const val = [value, timestamp] as [string, number];
if (!this.store[key]) {
this.store[key] = [val];
} else {
this.store[key].push(val);
}
}
get(key: string, timestamp: number): string {
let ans = '';
const val = this.store[key];
let left = 0;
let right = val.length - 1;
while (left <= right) {
const middle = ~~((left + right) / 2);
if (val[middle][1] <= timestamp) {
// if current timestamp is greater than the middle element's timestamp
// then we can set it to answer becasue we need to return the value
// associtated with the largest
ans = val[middle][0];
left = middle + 1;
} else {
right = middle - 1;
}
}
return ans;
}
}
/**
* Your TimeMap object will be instantiated and called as such:
* var obj = new TimeMap()
* obj.set(key,value,timestamp)
* var param_2 = obj.get(key,timestamp)
*/
// @lc code=end
微信id: 弘树 来自 vscode 插件
2022-10-11