模拟地铁系统进站出站,然后不断query两个站之间的平均通行时间,用python的一个dict存储从st到ed站之间的trip次数和总时间,另一个dict存储某个trip的进站和开始时间
1 #1396
2 #Runtime: 221 ms (Beats 56.41%)
3 #Memory: 25.4 MB (Beats 71.79%)
4
5 class UndergroundSystem(object):
6
7 def __init__(self):
8 self.trip_cur = {}
9 self.trip_his_data = {}
10
11
12 def checkIn(self, id, stationName, t):
13 """
14 :type id: int
15 :type stationName: str
16 :type t: int
17 :rtype: None
18 """
19 self.trip_cur[id] = (stationName, t)
20
21
22 def checkOut(self, id, stationName, t):
23 """
24 :type id: int
25 :type stationName: str
26 :type t: int
27 :rtype: None
28 """
29 sta, st = self.trip_cur.pop(id)
30 total_time, cnt = self.trip_his_data.get((sta, stationName), (0, 0))
31 self.trip_his_data[(sta, stationName)] = (total_time + t - st, cnt + 1)
32
33 def getAverageTime(self, startStation, endStation):
34 """
35 :type startStation: str
36 :type endStation: str
37 :rtype: float
38 """
39 total_time, cnt = self.trip_his_data.get((startStation, endStation))
40 return 1.0 * total_time / cnt
41
42
43
44 # Your UndergroundSystem object will be instantiated and called as such:
45 # obj = UndergroundSystem()
46 # obj.checkIn(id,stationName,t)
47 # obj.checkOut(id,stationName,t)
48 # param_3 = obj.getAverageTime(startStation,endStation)