diff --git a/javascript/4-Median-Of-Two-Sorted-Arrays.js b/javascript/4-Median-Of-Two-Sorted-Arrays.js new file mode 100644 index 000000000..1f364ac01 --- /dev/null +++ b/javascript/4-Median-Of-Two-Sorted-Arrays.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + let [A, B] = [nums1, nums2] + const total = nums1.length + nums2.length + const half = Math.floor(total / 2) + + if (B.length < A.length) { + [A, B] = [B, A] + } + + let [l, r] = [0, A.length -1] + while (true) { + const i = (l + r) + const j = half - i - 2 + + const Aleft = i >= 0 ? A[i] : -Infinity + const Aright = (i + 1) < A.length ? A[i + 1] : Infinity + const Bleft = j >= 0 ? B[j] : -Infinity + const Bright = (j + 1) < B.length ? B[j + 1] : Infinity + + if (Aleft <= Bright && Bleft <= Aright) { + if (total % 2) { + return Math.min(Aright, Bright) + } + + return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2 + } + else if (Aleft > Bright) r = i - 1 + else l = i + 1 + } +}; + diff --git a/javascript/981-Time-Based-Key-Value-Store.js b/javascript/981-Time-Based-Key-Value-Store.js new file mode 100644 index 000000000..2c19d7648 --- /dev/null +++ b/javascript/981-Time-Based-Key-Value-Store.js @@ -0,0 +1,44 @@ +var TimeMap = function() { + this.keyStore = {} +}; + +/** + * @param {string} key + * @param {string} value + * @param {number} timestamp + * @return {void} + */ +TimeMap.prototype.set = function(key, value, timestamp) { + if (!this.keyStore[key]) this.keyStore[key] = [] + this.keyStore[key].push([value, timestamp]) +}; + +/** + * @param {string} key + * @param {number} timestamp + * @return {string} + */ +TimeMap.prototype.get = function(key, timestamp) { + let res = "" + const values = this.keyStore[key] || [] + let l = 0, r = values.length -1 + + while (l <= r) { + const m = Math.floor((l + r) / 2) + if (values[m][1] <= timestamp) { + res = values[m][0] + l = m + 1 + } + else r = m - 1 + } + + return res +}; + +/** + * 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) + */ + pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy