题目描述:
python提交:
import collections class UndergroundSystem: def __init__(self): self.idloop = collections.defaultdict(list) self.count = collections.defaultdict(dict) def checkIn(self, id: int, stationName: str, t: int) -> None: self.idloop[id] = [stationName,t] def checkOut(self, id: int, stationName: str, t: int) -> None: if stationName not in self.count[self.idloop[id][0]]: self.count[self.idloop[id][0]][stationName] = [0,0] self.count[self.idloop[id][0]][stationName][0] += 1 self.count[self.idloop[id][0]][stationName][1] += t - self.idloop[id][1] self.idloop.pop(id) def getAverageTime(self, startStation: str, endStation: str) -> float: return self.count[startStation][endStation][1]/self.count[startStation][endStation][0]
java提交:
class UndergroundSystem { HashMap<String,Integer> sum = new HashMap<>(); HashMap<String,Integer> cnt = new HashMap<>(); HashMap<Integer,Pair> chi = new HashMap<>(); class Pair { String name; int start; Pair(String n,int t){ name = n; start = t; } } public UndergroundSystem() { } public void checkIn(int id, String s, int t) { chi.put(id, new Pair(s,t)); } public void checkOut(int id, String e, int t) { Pair p = chi.get(id); String tn = p.name+","+e; int v = sum.getOrDefault(tn,0) + t-p.start; sum.put(tn,v); int v1 = cnt.getOrDefault(tn,0) + 1; cnt.put(tn,v1); chi.remove(id); } public double getAverageTime(String s, String e) { int s1 = sum.getOrDefault(s+","+e,0); int v1 = cnt.getOrDefault(s+","+e,0); return s1*1.0/v1; } }