sadiqul_amin

1396. Design Underground System

Apr 24th, 2022
1,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. // 1396. Design Underground System
  2. // https://leetcode.com/problems/design-underground-system/
  3.  
  4. class UndergroundSystem {
  5.     private Map<String, Pair<Double, Double>> journeyData = new HashMap<>();
  6.     private Map<Integer, Pair<String, Integer>> checkInData = new HashMap<>();
  7.    
  8.     public UndergroundSystem() {
  9.     }
  10.    
  11.     public void checkIn(int id, String stationName, int t) {
  12.         checkInData.put(id, new Pair<>(stationName, t));
  13.     }
  14.    
  15.     public void checkOut(int id, String stationName, int t) {
  16.         // Look up the check in station and check in time for this id.
  17.         // You could combine this "unpacking" into the other lines of code
  18.         // to have less lines of code overall, but we've chosen to be verbose
  19.         // here to make it easy for all learners to follow.
  20.         Pair<String, Integer> checkInDataForId = checkInData.get(id);
  21.         String startStation = checkInDataForId.getKey();
  22.         Integer checkInTime = checkInDataForId.getValue();
  23.        
  24.         // Lookup the current travel time data for this route.
  25.         String routeKey = stationsKey(startStation, stationName);
  26.         Pair<Double, Double> routeStats  = journeyData.getOrDefault(routeKey, new Pair<>(0.0, 0.0));
  27.         Double totalTripTime = routeStats.getKey();
  28.         Double totalTrips = routeStats.getValue();
  29.        
  30.         // Update the travel time data with this trip.
  31.         double tripTime = t - checkInTime;
  32.         journeyData.put(routeKey, new Pair<>(totalTripTime + tripTime, totalTrips + 1));
  33.        
  34.         // Remove check in data for this id.
  35.         // Note that this is optional, we'll talk about it in the space complexity analysis.
  36.         checkInData.remove(id);
  37.     }
  38.    
  39.     public double getAverageTime(String startStation, String endStation) {
  40.         // Lookup how many times this journey has been made, and the total time.
  41.         String routeKey = stationsKey(startStation, endStation);
  42.         Double totalTime = journeyData.get(routeKey).getKey();
  43.         Double totalTrips = journeyData.get(routeKey).getValue();
  44.         // The average is simply the total divided by the number of trips.
  45.         return totalTime / totalTrips;
  46.     }
  47.    
  48.     private String stationsKey(String startStation, String endStation) {
  49.         return startStation + "->" + endStation;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment