Skip to content

Commit 3429848

Browse files
authored
Create 1348-tweet-counts-per-frequency.js
1 parent 5b9b274 commit 3429848

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

1348-tweet-counts-per-frequency.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
const createNode = val => ({ val, left: null, right: null });
2+
class BinarySearchTree {
3+
constructor() {
4+
this.root = null;
5+
}
6+
insert(val, cur = this.root) {
7+
const node = createNode(val);
8+
if (!this.root) { this.root = node; return; }
9+
if (val >= cur.val) {
10+
!cur.right ? (cur.right = node) : this.insert(val, cur.right);
11+
} else {
12+
!cur.left ? (cur.left = node) : this.insert(val, cur.left);
13+
}
14+
}
15+
traversal(low, high, interval, intervals, cur = this.root) {
16+
if (!cur) return;
17+
if (cur.val <= high && cur.val >= low) {
18+
++intervals[Math.floor((cur.val - low + 1) / interval)];
19+
}
20+
cur.val > low && this.traversal(low, high, interval, intervals, cur.left);
21+
cur.val < high && this.traversal(low, high, interval, intervals, cur.right);
22+
}
23+
};
24+
class TweetCounts {
25+
constructor() {
26+
this.freqInterval = {
27+
minute: 60,
28+
hour: 3600,
29+
day: 86400,
30+
};
31+
this.data = new Map();
32+
}
33+
34+
recordTweet(name, time) {
35+
if (this.data.has(name) === false) {
36+
this.data.set(name, new BinarySearchTree());
37+
}
38+
this.data.get(name).insert(time);
39+
}
40+
41+
getTweetCountsPerFrequency(freq, name, start, end) {
42+
const interval = this.freqInterval[freq];
43+
const ret = new Array(Math.ceil((end - start + 1) / interval)).fill(0);
44+
this.data.has(name) && this.data.get(name).traversal(start, end, interval, ret);
45+
return ret;
46+
}
47+
};
48+
49+
/**
50+
* Your TweetCounts object will be instantiated and called as such:
51+
* var obj = new TweetCounts()
52+
* obj.recordTweet(tweetName,time)
53+
* var param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
54+
*/

0 commit comments

Comments
 (0)