Skip to content

Commit 32d6eeb

Browse files
authored
Merge pull request neetcode-gh#418 from Ahmad-A0/main
Create 4-Median-Of-Two-Sorted-Arrays.js, 981-Time-Based-Key-Value-Store.js
2 parents 2923486 + 5c05c0d commit 32d6eeb

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} nums1
3+
* @param {number[]} nums2
4+
* @return {number}
5+
*/
6+
var findMedianSortedArrays = function(nums1, nums2) {
7+
let [A, B] = [nums1, nums2]
8+
const total = nums1.length + nums2.length
9+
const half = Math.floor(total / 2)
10+
11+
if (B.length < A.length) {
12+
[A, B] = [B, A]
13+
}
14+
15+
let [l, r] = [0, A.length -1]
16+
while (true) {
17+
const i = (l + r)
18+
const j = half - i - 2
19+
20+
const Aleft = i >= 0 ? A[i] : -Infinity
21+
const Aright = (i + 1) < A.length ? A[i + 1] : Infinity
22+
const Bleft = j >= 0 ? B[j] : -Infinity
23+
const Bright = (j + 1) < B.length ? B[j + 1] : Infinity
24+
25+
if (Aleft <= Bright && Bleft <= Aright) {
26+
if (total % 2) {
27+
return Math.min(Aright, Bright)
28+
}
29+
30+
return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2
31+
}
32+
else if (Aleft > Bright) r = i - 1
33+
else l = i + 1
34+
}
35+
};
36+
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
var TimeMap = function() {
2+
this.keyStore = {}
3+
};
4+
5+
/**
6+
* @param {string} key
7+
* @param {string} value
8+
* @param {number} timestamp
9+
* @return {void}
10+
*/
11+
TimeMap.prototype.set = function(key, value, timestamp) {
12+
if (!this.keyStore[key]) this.keyStore[key] = []
13+
this.keyStore[key].push([value, timestamp])
14+
};
15+
16+
/**
17+
* @param {string} key
18+
* @param {number} timestamp
19+
* @return {string}
20+
*/
21+
TimeMap.prototype.get = function(key, timestamp) {
22+
let res = ""
23+
const values = this.keyStore[key] || []
24+
let l = 0, r = values.length -1
25+
26+
while (l <= r) {
27+
const m = Math.floor((l + r) / 2)
28+
if (values[m][1] <= timestamp) {
29+
res = values[m][0]
30+
l = m + 1
31+
}
32+
else r = m - 1
33+
}
34+
35+
return res
36+
};
37+
38+
/**
39+
* Your TimeMap object will be instantiated and called as such:
40+
* var obj = new TimeMap()
41+
* obj.set(key,value,timestamp)
42+
* var param_2 = obj.get(key,timestamp)
43+
*/
44+

0 commit comments

Comments
 (0)