Design Underground System LeetCode solution in Java

1
class Passenger {
2
int checkinTime;
3
int checkoutTime;
4
String checkinLocation;
5
String checkoutLocation;
6

7
public Passenger(String checkinLocation, int checkinTime) {
8
this.checkinLocation = checkinLocation;
9
this.checkinTime = checkinTime;
10
}
11

12
void checkout(String checkoutLocation, int checkoutTime) {
13
this.checkoutLocation = checkoutLocation;
14
this.checkoutTime = checkoutTime;
15
}
16
}
17

18
class Route {
19
String startStation;
20
String endStation;
21
int totalNumberOfTrips;
22
long totalTimeSpentInTrips;
23

24
public Route(String startStation, String endStation) {
25
this.startStation = startStation;
26
this.endStation = endStation;
27
}
28

29
double getAverageTime() {
30
return (double) totalTimeSpentInTrips / totalNumberOfTrips;
31
}
32

33
void addTrip(int startTime, int endTime) {
34
totalTimeSpentInTrips += endTime - startTime;
35
totalNumberOfTrips++;
36
}
37
}
38

39
class UndergroundSystem {
40

41
Map<Integer, Passenger> currentPassengerMap;
42
Map<String, Route> routeMap;
43

44
public UndergroundSystem() {
45
currentPassengerMap = new HashMap<>();
46
routeMap = new HashMap<>();
47
}
48

49
public void checkIn(int id, String stationName, int t) {
50
if (!currentPassengerMap.containsKey(id)) {
51
Passenger passenger = new Passenger(stationName, t);
52
currentPassengerMap.put(id, passenger);
53
}
54
}
55

56
public void checkOut(int id, String stationName, int t) {
57
if (currentPassengerMap.containsKey(id)) {
58
Passenger passenger = currentPassengerMap.get(id);
59
passenger.checkout(stationName, t);
60
String routeKey = passenger.checkinLocation + "," + passenger.checkoutLocation;
61
Route route =
62
routeMap.getOrDefault(
63
routeKey, new Route(passenger.checkinLocation, passenger.checkoutLocation));
64
route.addTrip(passenger.checkinTime, passenger.checkoutTime);
65
routeMap.put(routeKey, route);
66
currentPassengerMap.remove(id);
67
}
68
}
69

70
public double getAverageTime(String startStation, String endStation) {
71
return routeMap.get(startStation + "," + endStation).getAverageTime();
72
}
73
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0