Problem link
https://leetcode.com/problems/design-underground-system/
Problem Summary
checkin, checkout을 통해 두 도시간의 평균 시간을 구하는 문제
Solution
그냥 간단하다. checkin 할 때는 map으로 id가 들어온 시각을 저장한 후 checkout 할때 해당 구간에 대해 걸린 시간과 카운트를 누적해서 더해주면 평균을 쉽게 구할 수 있다.
Source Code
class UndergroundSystem:
def __init__(self):
self.checkin = {}
self.timeSum = {}
self.cnt = {}
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.checkin[id] = (stationName, t)
def checkOut(self, id: int, stationName: str, t: int) -> None:
startStation, startTime = self.checkin.pop(id)
key = (startStation, stationName)
self.timeSum[key] = self.timeSum.get(key, 0) + t - startTime
self.cnt[key] = self.cnt.get(key, 0) + 1
def getAverageTime(self, startStation: str, endStation: str) -> float:
key = (startStation, endStation)
return self.timeSum[key] / self.cnt[key]
# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation)