← Static tasks

1396. Design Underground System

leetcode medium

#csharp#design#hash-table#leetcode#medium#string

Task

Подземная железнодорожная система отслеживает время поездок между станциями для вычисления среднего времени поездки от одной станции до другой.

Реализуйте класс UndergroundSystem:

- void checkIn(int id, string stationName, int t)

Пассажир с карточкой, идентификатор которой равен id, регистрируется на станции stationName в момент времени t.

Пассажир может быть зарегистрирован только в одном месте в одно и то же время.

- void checkOut(int id, string stationName, int t)

Пассажир с карточкой, идентификатор которой равен id, покидает станцию stationName в момент времени t.

- double getAverageTime(string startStation, string endStation)

Возвращает среднее время, необходимое для поездки от startStation до endStation.

Среднее время рассчитывается на основе всех предыдущих поездок от startStation до endStation, где пассажиры зарегистрировались на startStation и вышли на endStation. Время поездки от startStation до endStation может отличаться от времени поездки от endStation до startStation. Перед вызовом getAverageTime как минимум один пассажир уже совершил поездку от startStation до endStation. Предполагается, что все вызовы методов checkIn и checkOut последовательны и происходят в хронологическом порядке.

Пример:

Input

["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]

[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]

Output

[null,null,null,5.00000,null,null,5.50000]

Explanation

UndergroundSystem undergroundSystem = new UndergroundSystem();

undergroundSystem.checkIn(10, "Leyton", 3);

undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5

undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5

undergroundSystem.checkIn(5, "Leyton", 10);

undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6

undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5

C# solution

matched/original
public class UndergroundSystem {
    private Dictionary<string, (double totalTime, double trips)> journeyData = new Dictionary<string, (double, double)>();
    private Dictionary<int, (string stationName, int time)> checkInData = new Dictionary<int, (string, int)>();
    public void CheckIn(int id, string stationName, int t) {
        checkInData[id] = (stationName, t);
    }
    public void CheckOut(int id, string stationName, int t) {
        var (startStation, startTime) = checkInData[id];
        checkInData.Remove(id);
        var routeKey = $"{startStation}->{stationName}";
        var tripTime = t - startTime;
        if (!journeyData.ContainsKey(routeKey)) {
            journeyData[routeKey] = (0, 0);
        }
        var (totalTime, trips) = journeyData[routeKey];
        journeyData[routeKey] = (totalTime + tripTime, trips + 1);
    }
    public double GetAverageTime(string startStation, string endStation) {
        var (totalTime, trips) = journeyData[$"{startStation}->{endStation}"];
        return totalTime / trips;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class UndergroundSystem {
    private unordered_map<string, (double totalTime, double trips)> journeyData = new unordered_map<string, (double, double)>();
    private unordered_map<int, (string stationName, int time)> checkInData = new unordered_map<int, (string, int)>();
    public void CheckIn(int id, string stationName, int t) {
        checkInData[id] = (stationName, t);
    }
    public void CheckOut(int id, string stationName, int t) {
        var (startStation, startTime) = checkInData[id];
        checkInData.Remove(id);
        var routeKey = $"{startStation}->{stationName}";
        var tripTime = t - startTime;
        if (!journeyData.count(routeKey)) {
            journeyData[routeKey] = (0, 0);
        }
        var (totalTime, trips) = journeyData[routeKey];
        journeyData[routeKey] = (totalTime + tripTime, trips + 1);
    }
    public double GetAverageTime(string startStation, string endStation) {
        var (totalTime, trips) = journeyData[$"{startStation}->{endStation}"];
        return totalTime / trips;
    }
}

Java solution

matched/original
class UndergroundSystem {
    private Map<String, double[]> journeyData = new HashMap<>();
    private Map<Integer, Pair<String, Integer>> checkInData = new HashMap<>();

    public void checkIn(int id, String stationName, int t) {
        checkInData.put(id, new Pair<>(stationName, t));
    }

    public void checkOut(int id, String stationName, int t) {
        Pair<String, Integer> checkIn = checkInData.remove(id);
        String routeKey = checkIn.getKey() + "->" + stationName;
        double tripTime = t - checkIn.getValue();
        journeyData.computeIfAbsent(routeKey, k -> new double[2]);
        journeyData.get(routeKey)[0] += tripTime;
        journeyData.get(routeKey)[1] += 1;
    }

    public double getAverageTime(String startStation, String endStation) {
        double[] stats = journeyData.get(startStation + "->" + endStation);
        return stats[0] / stats[1];
    }
}

JavaScript solution

matched/original
class UndergroundSystem {
    constructor() {
        this.journeyData = new Map();
        this.checkInData = new Map();
    }

    checkIn(id, stationName, t) {
        this.checkInData.set(id, [stationName, t]);
    }

    checkOut(id, stationName, t) {
        const [startStation, startTime] = this.checkInData.get(id);
        this.checkInData.delete(id);
        const routeKey = `${startStation}->${stationName}`;
        const tripTime = t - startTime;
        if (!this.journeyData.has(routeKey)) {
            this.journeyData.set(routeKey, [0, 0]);
        }
        const [totalTime, trips] = this.journeyData.get(routeKey);
        this.journeyData.set(routeKey, [totalTime + tripTime, trips + 1]);
    }

    getAverageTime(startStation, endStation) {
        const [totalTime, trips] = this.journeyData.get(`${startStation}->${endStation}`);
        return totalTime / trips;
    }
}

Go solution

matched/original
type UndergroundSystem struct {
    journeyData map[string][2]float64
    checkInData map[int][2]interface{}
}

func Constructor() UndergroundSystem {
    return UndergroundSystem{
        journeyData: make(map[string][2]float64),
        checkInData: make(map[int][2]interface{}),
    }
}

func (this *UndergroundSystem) CheckIn(id int, stationName string, t int) {
    this.checkInData[id] = [2]interface{}{stationName, t}
}

func (this *UndergroundSystem) CheckOut(id int, stationName string, t int) {
    checkIn := this.checkInData[id]
    startStation := checkIn[0].(string)
    startTime := checkIn[1].(int)
    delete(this.checkInData, id)
    routeKey := startStation + "->" + stationName
    tripTime := float64(t - startTime)
    if _, exists := this.journeyData[routeKey]; !exists {
        this.journeyData[routeKey] = [2]float64{0, 0}
    }
    this.journeyData[routeKey][0] += tripTime
    this.journeyData[routeKey][1] += 1
}

func (this *UndergroundSystem) GetAverageTime(startStation string, endStation string) float64 {
    stats := this.journeyData[startStation+"->"+endStation]
    return stats[0] / stats[1]
}

Explanation

Algorithm

При регистрации на входе сохраняем информацию о начале пути (станция и время) в словаре checkInData.

При регистрации на выходе извлекаем информацию о начале пути из checkInData, вычисляем время поездки и обновляем статистику для маршрута в journeyData.

Для получения среднего времени поездки по заданному маршруту извлекаем статистику из journeyData и вычисляем среднее значение.

😎