Skip to content

Commit 39ef606

Browse files
authored
Create 3508. Implement Router (#890)
2 parents 4129157 + ade4677 commit 39ef606

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

3508. Implement Router

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class Router {
2+
public:
3+
int limit = 0;
4+
set<vector<int>> packets;
5+
unordered_map<int, int> removedPacketsFromDestination;
6+
unordered_map<int, vector<int>> pD;
7+
8+
queue<vector<int>> q;
9+
Router(int memoryLimit) { limit = memoryLimit; }
10+
11+
bool addPacket(int source, int destination, int timestamp) {
12+
if (packets.find({source, destination, timestamp}) != packets.end()) {
13+
return false;
14+
}
15+
if (q.size() > 0) {
16+
17+
if (limit == q.size()) {
18+
19+
vector<int> p = q.front();
20+
21+
packets.erase(p);
22+
removedPacketsFromDestination[p[1]]++;
23+
24+
q.pop();
25+
}
26+
}
27+
28+
q.push({source, destination, timestamp});
29+
pD[destination].push_back(timestamp);
30+
packets.insert({source, destination, timestamp});
31+
return true;
32+
}
33+
34+
vector<int> forwardPacket() {
35+
if (q.size() > 0) {
36+
vector<int> p = q.front();
37+
packets.erase(p);
38+
removedPacketsFromDestination[p[1]]++;
39+
q.pop();
40+
return p;
41+
}
42+
43+
return {};
44+
}
45+
46+
int getCount(int destination, int startTime, int endTime) {
47+
48+
if (pD.find(destination) == pD.end()) {
49+
return 0;
50+
}
51+
52+
int x = removedPacketsFromDestination[destination];
53+
54+
auto it = lower_bound(pD[destination].begin() + x,
55+
pD[destination].end(), startTime);
56+
57+
auto it2 = upper_bound(pD[destination].begin() + x,
58+
pD[destination].end(), endTime);
59+
60+
int count = int(it2 - it);
61+
return count;
62+
}
63+
};
64+
65+
/**
66+
* Your Router object will be instantiated and called as such:
67+
* Router* obj = new Router(memoryLimit);
68+
* bool param_1 = obj->addPacket(source,destination,timestamp);
69+
* vector<int> param_2 = obj->forwardPacket();
70+
* int param_3 = obj->getCount(destination,startTime,endTime);
71+
*/

0 commit comments

Comments
 (0)