[python][leetcode 1396] Design Underground System

Dawon Seo·2023년 5월 31일
0
post-thumbnail

1. 문제

An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

Implement the UndergroundSystem class:

void checkIn(int id, string stationName, int t)
A customer with a card ID equal to id, checks in at the station stationName at time t.
A customer can only be checked into one place at a time.
void checkOut(int id, string stationName, int t)
A customer with a card ID equal to id, checks out from the station stationName at time t.
double getAverageTime(string startStation, string endStation)
Returns the average time it takes to travel from startStation to endStation.
The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.
You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

지하철 시스템을 구현해라.
void checkIn(int id, string stationName, int t)
id에 해당하는 고객이 시간 t에 stationName에서 체크인합니다.
void checkOut(int id, string stationName, int t)
id에 해당하는 고객이 시간 t에 stationName에서 체크아웃합니다.
double getAverageTime(string startStation, string endStation)
startStation에서 endStation까지 이동하는 데 걸리는 평균 시간을 반환합니다.

2. 내 풀이

class UndergroundSystem:

    def __init__(self):
        self.dict1 = {}
        self.dict2 = {}

    def checkIn(self, id: int, stationName: str, t: int) -> None:
        self.dict1[id] = (stationName, t)

    def checkOut(self, id: int, stationName: str, t: int) -> None:
        s, st = self.dict1[id]
        del self.dict1[id]
        if (s, stationName) in self.dict2.keys():
            a, b = self.dict2[(s, stationName)]
            self.dict2[(s, stationName)] = (a + 1, b + (t - st))
        else:
            self.dict2[(s, stationName)] = (1, t - st)

    def getAverageTime(self, startStation: str, endStation: str) -> float:
        a, b = self.dict2[(startStation, endStation)]
        return b / a
  1. dict1은 {고객id: (역 이름, 출발 시간)} 데이터를 보관
  2. dict2는 {(출발역, 도착역): (고객 수, 총 걸린 시간 합)}을 보관
  3. checkIn 호출 시 dict1에 {고객id: (역 이름, 출발 시간)} 쌍을 저장
  4. checkOut 호출 시 dict1[id] 데이터를 가져와 dict2 데이터를 업데이트합니다.
  5. getAverageTime 호출 시 dict2에서 (출발역, 도착역) Key의 값을 찾아 (총 걸린 시간 합) / (고객 수)를 반환합니다.

3. 느낀점

이런 류의 문제를 푸는 데에는 역시 dictionary를 잘 활용하는 게 중요한 것 같다.

0개의 댓글