-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDesign Underground System.java
74 lines (60 loc) · 2.23 KB
/
Design Underground System.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Runtime: 92 ms (Top 65.05%) | Memory: 55.90 MB (Top 20.97%)
class Passenger {
int checkinTime;
int checkoutTime;
String checkinLocation;
String checkoutLocation;
public Passenger(String checkinLocation, int checkinTime) {
this.checkinLocation = checkinLocation;
this.checkinTime = checkinTime;
}
void checkout(String checkoutLocation, int checkoutTime) {
this.checkoutLocation = checkoutLocation;
this.checkoutTime = checkoutTime;
}
}
class Route {
String startStation;
String endStation;
int totalNumberOfTrips;
long totalTimeSpentInTrips;
public Route(String startStation, String endStation) {
this.startStation = startStation;
this.endStation = endStation;
}
double getAverageTime() {
return (double) totalTimeSpentInTrips / totalNumberOfTrips;
}
void addTrip(int startTime, int endTime) {
totalTimeSpentInTrips += endTime - startTime;
totalNumberOfTrips++;
}
}
class UndergroundSystem {
Map<Integer, Passenger> currentPassengerMap;
Map<String, Route> routeMap;
public UndergroundSystem() {
currentPassengerMap = new HashMap<>();
routeMap = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
if (!currentPassengerMap.containsKey(id)) {
Passenger passenger = new Passenger(stationName, t);
currentPassengerMap.put(id, passenger);
}
}
public void checkOut(int id, String stationName, int t) {
if (currentPassengerMap.containsKey(id)) {
Passenger passenger = currentPassengerMap.get(id);
passenger.checkout(stationName, t);
String routeKey = passenger.checkinLocation + "," + passenger.checkoutLocation;
Route route = routeMap.getOrDefault(routeKey, new Route(passenger.checkinLocation, passenger.checkoutLocation));
route.addTrip(passenger.checkinTime, passenger.checkoutTime);
routeMap.put(routeKey, route);
currentPassengerMap.remove(id);
}
}
public double getAverageTime(String startStation, String endStation) {
return routeMap.get(startStation + "," + endStation).getAverageTime();
}
}