zoukankan      html  css  js  c++  java
  • leetcode1396

     1 class UndergroundSystem:
     2     def __init__(self):
     3         self.startStation = collections.defaultdict(lambda: collections.defaultdict(int))
     4         self.endStation = collections.defaultdict(lambda: collections.defaultdict(int))
     5 
     6     def checkIn(self, id: int, stationName: str, t: int) -> None:
     7         self.startStation[stationName][id] = t
     8         
     9     def checkOut(self, id: int, stationName: str, t: int) -> None:
    10         self.endStation[stationName][id] = t
    11         
    12     def getAverageTime(self, startStation: str, endStation: str) -> float:
    13         time = 0
    14         customers = 0
    15         for id in self.endStation[endStation]:
    16             if id in self.startStation[startStation]:
    17                 customers += 1
    18                 time += self.endStation[endStation][id] - self.startStation[startStation][id]
    19         
    20         return time / customers if time else 0 

    参考:https://leetcode.com/problems/design-underground-system/discuss/554871/Python3-Easy-Python-with-dict

    我自己的代码是下面的,第51个testcase,总是通不过,不知道是float的精度问题还是数值计算的不对:

     1 class Station:
     2     def __init__(self):
     3         self.startStation = ''
     4         self.startTime = -1.0
     5         self.endStation = ''
     6         self.endTime = -1.0
     7 
     8 class UndergroundSystem:
     9 
    10     def __init__(self):
    11         self.dic = dict()#以cardid为key
    12 
    13     def checkIn(self, id: int, stationName: str, t: int) -> None:
    14         station = Station()
    15         station.startStation = stationName
    16         station.startTime = t
    17         self.dic[id] = station
    18 
    19     def checkOut(self, id: int, stationName: str, t: int) -> None:
    20         self.dic[id].endStation = stationName
    21         self.dic[id].endTime = t
    22 
    23     def getAverageTime(self, startStation: str, endStation: str) -> float:
    24         count = 0
    25         sums = 0
    26         for id,record in self.dic.items():
    27             if record.startStation == startStation and record.endStation == endStation:
    28                 count += 1.0
    29                 sums += float(record.endTime - record.startTime)
    30         return round(float(sums) / count, 1) if count != 0 else 0
  • 相关阅读:
    vue之前端鉴权
    vue jsx与render的区别及基本使用
    vue-svgicon基本使用
    vue-cli 3.0按需引入element-ui
    手动实现Promise
    checkbox、radio设置自定义样式
    AngularJS之拖拽排序(ngDraggable.js)
    webpack 4.x之搭建前端开发环境
    VUE,基于vue-cli搭建创建vue项目
    ES6面向对象 动态添加标签页
  • 原文地址:https://www.cnblogs.com/asenyang/p/12591712.html
Copyright © 2011-2022 走看看