1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Router:
def __init__(self, memoryLimit: int): self.max_len = memoryLimit self.packs = deque() self.packSet = set() self.dest_to_timestamp = defaultdict(deque)
def addPacket(self, source: int, destination: int, timestamp: int) -> bool: pack = (source, destination, timestamp) if pack in self.packSet: return False if len(self.packs) >= self.max_len: self.forwardPacket() self.packSet.add(pack) self.packs.append([source, destination, timestamp]) self.dest_to_timestamp[destination].append(timestamp) return True
def forwardPacket(self) -> List[int]: if self.packs: res = self.packs.popleft() self.dest_to_timestamp[res[1]].popleft() self.packSet.remove(tuple(res)) else: res = [] return res
def getCount(self, destination: int, startTime: int, endTime: int) -> int: q = self.dest_to_timestamp[destination] l = bisect_left(q, startTime) r = bisect_right(q, endTime) return r - l
|