标签:python checkin self System dict stationName Design startStation id
题目
错误解法
先分享一种错误解法。下面的这种错误解法错在很多个点上。首先,他每个操作不是O(1)的,时间复杂度就错了。第二,如果某个id先进出某两个站,然后再进了某个站,这个时候计算他的travel time是错的,因为按照下面这种解法会是出站时间小于进站时间,也就是这种解法不满足同一个id多次进出的情况。第三,如果某个idA进B出,然后C进D出,这个时候按下面的解法,在query(A,D)这个pair的时候就会被错误的包括进去,所以start和end必须是以pair的形式储存的
class UndergroundSystem:
def __init__(self):
self.checkin_dict = {}
self.checkout_dict = {}
def checkIn(self, id: int, stationName: str, t: int) -> None:
if stationName in self.checkin_dict:
self.checkin_dict[stationName][id] = t
else:
self.checkin_dict[stationName] = {}
self.checkin_dict[stationName][id] = t
def checkOut(self, id: int, stationName: str, t: int) -> None:
if stationName in self.checkout_dict:
self.checkout_dict[stationName][id] = t
else:
self.checkout_dict[stationName] = {}
self.checkout_dict[stationName][id] = t
def getAverageTime(self, startStation: str, endStation: str) -> float:
#print(self.checkin_dict)
total_time = 0
cnt = 0
if startStation in self.checkin_dict and endStation in self.checkout_dict:
for id,t in self.checkin_dict[startStation].items():
if id in self.checkout_dict[endStation]:
cnt += 1
total_time += self.checkout_dict[endStation][id] - self.checkin_dict[startStation][id]
return total_time/cnt
正确解法
这道题正确解法远没有这么复杂。前面这么些是因为默认了checkin和checkout的情况需要被储存下来,其实只要储存checkin,checkout的时候就可以直接计算相应的时间了
class UndergroundSystem:
def __init__(self):
self.checkin_dict = {}
self.travel_time = collections.defaultdict(int)
self.travel_cnt = collections.defaultdict(int)
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.checkin_dict[id] = (stationName,t)
def checkOut(self, id: int, stationName: str, t: int) -> None:
startStation,start_t = self.checkin_dict[id]
self.travel_time[(startStation,stationName)] += t - start_t
self.travel_cnt[(startStation,stationName)] += 1
def getAverageTime(self, startStation: str, endStation: str) -> float:
return self.travel_time[(startStation,endStation)]/self.travel_cnt[(startStation,endStation)]
标签:python,checkin,self,System,dict,stationName,Design,startStation,id 来源: https://blog.csdn.net/qq_37821701/article/details/111244971
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。