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(); } } Leetcode > Medium #Leetcode #心得 #String #Hash Table #Design 1396. Design Underground System - Medium https://f88083.github.io/2024/03/28/1396-Design-Underground-System-Medium/ 作者 Simon Lai 發布於 2024年3月28日 許可協議 535. Encode and Decode TinyURL - Medium 上一篇 1603. Design Parking System - Easy 下一篇 Please enable JavaScript to view the comments