1396. Design Underground System

An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

Implement the UndergroundSystem class:

  • void checkIn(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks in at 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, checks out from the station stationName at time t.
  • double getAverageTime(string startStation, string endStation)
    • Returns the average time it takes to travel from startStation to endStation.
    • The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
    • The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
    • There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.
      You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

两个哈希表,第一个暂存id。第二个用来储存“站点——站点”和路线中的总用时,路线中的总人数。
最后返回总用时除以总人数。
(一开始采用的算法没有考虑id重复进站,和id出站进站不同的情况。)

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
class UndergroundSystem {
HashMap<Integer, Pair<String, Integer>> inMap;
HashMap<String, int[]> outMap;
public UndergroundSystem() {
inMap = new HashMap<Integer, Pair<String, Integer>>();
outMap = new HashMap<String, int[]>();
}

public void checkIn(int id, String stationName, int t) {
Pair<String, Integer> data = new Pair(stationName, t);
inMap.put(id, data);
}

public void checkOut(int id, String stationName, int t) {
Pair<String, Integer> data = inMap.get(id);
String route = data.getKey() + "-" + stationName;

int[] routeData = outMap.getOrDefault(route, new int[2]);
routeData[0] += t - data.getValue();
routeData[1]++;

outMap.put(route, routeData);
}

public double getAverageTime(String startStation, String endStation) {
String route = startStation + "-" + endStation;
return outMap.get(route)[0] / (double) outMap.get(route)[1];
}
}

/**
* 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

Xander

Posted on

2022-04-24

Updated on

2022-04-24

Licensed under

Comments