|
| 1 | +/** |
| 2 | + * 981. Time Based Key-Value Store |
| 3 | + * https://leetcode.com/problems/time-based-key-value-store/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design a time-based key-value data structure that can store multiple values for the same key |
| 7 | + * at different time stamps and retrieve the key's value at a certain timestamp. |
| 8 | + * |
| 9 | + * Implement the TimeMap class: |
| 10 | + * - TimeMap() Initializes the object of the data structure. |
| 11 | + * - void set(String key, String value, int timestamp) Stores the key key with the value value |
| 12 | + * at the given time timestamp. |
| 13 | + * - String get(String key, int timestamp) Returns a value such that set was called previously, |
| 14 | + * with timestamp_prev <= timestamp. If there are multiple such values, it returns the value |
| 15 | + * associated with the largest timestamp_prev. If there are no values, it returns "". |
| 16 | + */ |
| 17 | + |
| 18 | +var TimeMap = function() { |
| 19 | + this.store = new Map(); |
| 20 | +}; |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string} key |
| 24 | + * @param {string} value |
| 25 | + * @param {number} timestamp |
| 26 | + * @return {void} |
| 27 | + */ |
| 28 | +TimeMap.prototype.set = function(key, value, timestamp) { |
| 29 | + if (!this.store.has(key)) this.store.set(key, []); |
| 30 | + this.store.get(key).push([timestamp, value]); |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * @param {string} key |
| 35 | + * @param {number} timestamp |
| 36 | + * @return {string} |
| 37 | + */ |
| 38 | +TimeMap.prototype.get = function(key, timestamp) { |
| 39 | + if (!this.store.has(key)) return ''; |
| 40 | + const entries = this.store.get(key); |
| 41 | + let left = 0; |
| 42 | + let right = entries.length - 1; |
| 43 | + |
| 44 | + while (left <= right) { |
| 45 | + const mid = Math.floor((left + right) / 2); |
| 46 | + const [midTime, midValue] = entries[mid]; |
| 47 | + |
| 48 | + if (midTime === timestamp) return midValue; |
| 49 | + if (midTime < timestamp) left = mid + 1; |
| 50 | + else right = mid - 1; |
| 51 | + } |
| 52 | + |
| 53 | + return right >= 0 ? entries[right][1] : ''; |
| 54 | +}; |
0 commit comments