1396. Design Underground System - Medium

前往題目

想法

  • OOP

思路

  1. 乘客class,紀錄checkincheckout時間地點
  2. 路線class, 紀錄起站終站以及總共花費時間和次數
  3. Mapid和乘客連接起來,路線和路線class連接起來

checkin:把乘客資訊加入即可

checkout:把乘客checkout,更新或加入路徑,最後移除乘客資訊,因為checkout

average:直接找到該路徑,然後調用路徑classaverage就可以算出來

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/
作者
Simon Lai
發布於
2024年3月28日
許可協議