July 24, 2022

1396. Design Underground System

1396. Design Underground System

两个HashMap.
HashMap1: Key: id; value: Pair<startStationName, startTime> HashMap2: Key: startStationName->endStationName; value: Pair<totalTime, totalTrips>

class UndergroundSystem {
    
    private Map<Integer, Pair> checkInMap;
    private Map<String, Pair<Double, Double>> avgMap;

    public UndergroundSystem() {
        checkInMap = new HashMap<>();
        avgMap = new HashMap<>();
    }
    
    public void checkIn(int id, String stationName, int t) {
        checkInMap.put(id, new Pair<>(stationName, t));
    }
    
    public void checkOut(int id, String stationName, int t) {
        Pair<String, Integer> checkInDataForId = checkInMap.get(id);
        String startStation = checkInDataForId.getKey();
        int checkInTime = checkInDataForId.getValue();
        String endStation = stationName;
        int checkOutTime = t;
        String routeKey = startStation + "->" + endStation;
        Pair<Double, Double> routeStats = avgMap.getOrDefault(routeKey, new Pair<>(0.0, 0.0));
        double totalTripTime = routeStats.getKey();
        double totalTrips = routeStats.getValue();
        
        double tripTime = checkOutTime - checkInTime;
        avgMap.put(routeKey, new Pair<>(totalTripTime + tripTime, totalTrips + 1));
        checkInMap.remove(id);
    }
    
    public double getAverageTime(String startStation, String endStation) {
        String routeKey = startStation + "->" + endStation;
        double TotalTime = avgMap.get(routeKey).getKey();
        double TotalTrips = avgMap.get(routeKey).getValue();
        return TotalTime / TotalTrips;
    }
}

/**
 * Your UndergroundSystem object will be instantiated and called as such:
 * UndergroundSystem obj = new UndergroundSystem();
 * obj.checkIn(id,stationName,t);
 * obj.checkOut(id,stationName,t);
 * double param_3 = obj.getAverageTime(startStation,endStation);
 */
comments powered by Disqus