1396. Design Underground System - Medium
前往題目
想法
- 用
OOP
解
思路
- 乘客
class
,紀錄checkin
和checkout
時間地點 - 路線
class
, 紀錄起站終站以及總共花費時間和次數 - 用
Map
把id
和乘客連接起來,路線和路線class
連接起來
checkin
:把乘客資訊加入即可
checkout
:把乘客checkout
,更新或加入路徑,最後移除乘客資訊,因為checkout
了
average
:直接找到該路徑,然後調用路徑class
的average
就可以算出來
Code
留言區解答class UndergroundSystem {
class Passenger {
int checkInTime;
int checkOutTime;
String checkInStation;
String checkOutStation;
public Passenger(String checkInStation, int checkInTime) {
this.checkInStation = checkInStation;
this.checkInTime = checkInTime;
}
public void checkOut(String checkOutStation, int checkOutTime) {
this.checkOutStation = checkOutStation;
this.checkOutTime = checkOutTime;
}
}
class Route {
String startStation;
String endStation;
int totalTrips;
long totalTimeSpentInTrips;
public Route(String startStation, String endStation) {
this.startStation = startStation;
this.endStation = endStation;
}
public void addTrip(int startTime, int endTime) {
totalTimeSpentInTrips += endTime - startTime;
totalTrips += 1;
}
public double getAverage() {
return (double) totalTimeSpentInTrips / totalTrips;
}
}
Map<Integer, Passenger> passengerMap;
Map<String, Route> routeMap;
public UndergroundSystem() {
passengerMap = new HashMap<>();
routeMap = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
if (!passengerMap.containsKey(id)) {
// CheckIn
passengerMap.put(id, new Passenger(stationName, t));
}
}
public void checkOut(int id, String stationName, int t) {
if (passengerMap.containsKey(id)) {
// Check out
Passenger p = passengerMap.get(id);
p.checkOut(stationName, t);
// Adding or update route
String routeKey = p.checkInStation + "," + p.checkOutStation;
Route route = routeMap.getOrDefault(routeKey, new Route(p.checkInStation, p.checkOutStation));
route.addTrip(p.checkInTime, p.checkOutTime);
// Update route
routeMap.put(routeKey, route);
// Remove the passenger since checkout already
passengerMap.remove(id);
}
}
public double getAverageTime(String startStation, String endStation) {
return routeMap.get(startStation + "," + endStation).getAverage();
}
}
1396. Design Underground System - Medium
https://f88083.github.io/2024/03/28/1396-Design-Underground-System-Medium/