[LeetCode] Design Underground System

1396. Design Underground System

Implement the UndergroundSystem class:

  • void checkIn(int id, string stationName, int t)

    • A customer with a card id equal to id, gets in the station stationName at time t.
    • A customer can only be checked into one place at a time.
  • void checkOut(int id, string stationName, int t)

    • A customer with a card id equal to id, gets out from the station stationName at time t.
  • double getAverageTime(string startStation, string endStation)

    • Returns the average time to travel between the startStation and the endStation.
    • The average time is computed from all the previous traveling from startStation to endStation that happened directly.
    • Call to getAverageTime is always valid.

You can assume all calls to checkIn and checkOut methods are consistent. If a customer gets in at time t1 at some station, they get out at time t2 with t2 > t1. All events happen in chronological order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class UndergroundSystem {
private:
map<pair<string, string>, pair<long, int>> avgTime;
map<int, pair<string, int>> checkInMap;
public:
UndergroundSystem() {

}

void checkIn(int id, string stationName, int t) {
checkInMap[id] = {stationName, t};

return;
}

void checkOut(int id, string stationName, int t) {
auto in = checkInMap[id];
if(!avgTime.count({in.first, stationName})) {
avgTime[{in.first, stationName}] = {0, 0};
}
avgTime[{in.first, stationName}].first += t - in.second;
avgTime[{in.first, stationName}].second += 1;

return;
}

double getAverageTime(string startStation, string endStation) {
return 1.0 * avgTime[{startStation, endStation}].first / avgTime[{startStation, endStation}].second;
}
};

/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem* obj = new UndergroundSystem();
* obj->checkIn(id,stationName,t);
* obj->checkOut(id,stationName,t);
* double param_3 = obj->getAverageTime(startStation,endStation);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/20/PS/LeetCode/design-underground-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.