返回

LeetCode 1396:地铁系统的设计(Python)

后端

引言

在 LeetCode 1396:地铁系统的设计中,我们被要求设计一个地铁系统,该系统支持以下操作:

  • checkIn(int stationId, int timestamp):乘客在某个车站进站。
  • checkOut(int stationId, int timestamp):乘客在某个车站出站。
  • getAverageTime(int startStationId, int endStationId):计算乘客从某个车站到另一个车站的平均旅行时间。

实现

我们可以使用哈希表来存储每个车站的进出站信息。哈希表中的键为车站 ID,值是一个元组,其中第一个元素为乘客进站时间列表,第二个元素为乘客出站时间列表。

为了计算乘客的旅行时间,我们需要找出乘客在起始车站和终点车站的进出站时间。然后,我们可以将出站时间减去进站时间得到乘客的旅行时间。最后,我们将所有乘客的旅行时间求和并除以乘客总数得到平均旅行时间。

以下是如何用 Python 实现该算法:

class UndergroundSystem:

    def __init__(self):
        self.checkin_info = {}
        self.checkout_info = {}
        self.total_time = {}
        self.passenger_count = {}

    def checkIn(self, stationId: int, timestamp: int) -> None:
        if stationId not in self.checkin_info:
            self.checkin_info[stationId] = [timestamp]
        else:
            self.checkin_info[stationId].append(timestamp)

    def checkOut(self, stationId: int, timestamp: int) -> None:
        if stationId not in self.checkout_info:
            self.checkout_info[stationId] = [timestamp]
        else:
            self.checkout_info[stationId].append(timestamp)

        for checkin_time in self.checkin_info[stationId]:
            total_time = timestamp - checkin_time
            if (stationId, stationId) not in self.total_time:
                self.total_time[(stationId, stationId)] = [total_time]
                self.passenger_count[(stationId, stationId)] = 1
            else:
                self.total_time[(stationId, stationId)].append(total_time)
                self.passenger_count[(stationId, stationId)] += 1
            del self.checkin_info[stationId][self.checkin_info[stationId].index(checkin_time)]

    def getAverageTime(self, startStationId: int, endStationId: int) -> float:
        if (startStationId, endStationId) not in self.total_time:
            return 0.0
        else:
            return sum(self.total_time[(startStationId, endStationId)]) / self.passenger_count[(startStationId, endStationId)]

示例

undergroundSystem = UndergroundSystem()
undergroundSystem.checkIn(45, 10)
undergroundSystem.checkIn(50, 25)
undergroundSystem.checkOut(50, 60)
undergroundSystem.checkOut(45, 85)
print(undergroundSystem.getAverageTime(45, 50))  # 输出:50.0

结论

使用哈希表和平均旅行时间,我们可以高效地设计一个地铁系统,支持进站、出站和获取平均旅行时间操作。通过以上实现,我们可以轻松解决 LeetCode 1396:地铁系统的设计问题。