-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdesign-underground-system.java
48 lines (40 loc) · 2.17 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
class UndergroundSystem {
private Map<String, Pair<Double, Double>> journeyData = new HashMap<>();
private Map<Integer, Pair<String, Integer>> checkInData = new HashMap<>();
public UndergroundSystem() {
}
public void checkIn(int id, String stationName, int t) {
checkInData.put(id, new Pair<>(stationName, t));
}
public void checkOut(int id, String stationName, int t) {
// Look up the check in station and check in time for this id.
// You could combine this "unpacking" into the other lines of code
// to have less lines of code overall, but we've chosen to be verbose
// here to make it easy for all learners to follow.
Pair<String, Integer> checkInDataForId = checkInData.get(id);
String startStation = checkInDataForId.getKey();
Integer checkInTime = checkInDataForId.getValue();
// Lookup the current travel time data for this route.
String routeKey = stationsKey(startStation, stationName);
Pair<Double, Double> routeStats = journeyData.getOrDefault(routeKey, new Pair<>(0.0, 0.0));
Double totalTripTime = routeStats.getKey();
Double totalTrips = routeStats.getValue();
// Update the travel time data with this trip.
double tripTime = t - checkInTime;
journeyData.put(routeKey, new Pair<>(totalTripTime + tripTime, totalTrips + 1));
// Remove check in data for this id.
// Note that this is optional, we'll talk about it in the space complexity analysis.
checkInData.remove(id);
}
public double getAverageTime(String startStation, String endStation) {
// Lookup how many times this journey has been made, and the total time.
String routeKey = stationsKey(startStation, endStation);
Double totalTime = journeyData.get(routeKey).getKey();
Double totalTrips = journeyData.get(routeKey).getValue();
// The average is simply the total divided by the number of trips.
return totalTime / totalTrips;
}
private String stationsKey(String startStation, String endStation) {
return startStation + "->" + endStation;
}
}