- Leetcode 3508. Implement Router
- 1. 解题思路
- 2. 代码实现
- 题目链接:3508. Implement Router
1. 解题思路
这一题就是按照题意写作一下对应的函数即可。
我们需要注意的是,这里,定义的类当中需要包含以下一些内容:
- 一个所有item的集合,来快速判断当前给到的包是否已经出现过了;
- 一个按照时间戳以及输入顺序有序排列的所有package的队列,从而确保可以弹出最早的包;
- 一个按照destination进行分块,且各自按照timestamp进行有序排列的序列,从而使得可以对
getCount
函数进行快速实现。
2. 代码实现
给出python代码实现如下:
class Router:def __init__(self, memoryLimit: int):self.idx = 0self.memoryLimit = memoryLimitself.seen = set()self.packets = []self.groups = defaultdict(list)def addPacket(self, source: int, destination: int, timestamp: int) -> bool:if (source, destination, timestamp) in self.seen:return Falseif len(self.packets) == self.memoryLimit:self.forwardPacket()self.seen.add((source, destination, timestamp))bisect.insort(self.packets, (timestamp, self.idx, source, destination))bisect.insort(self.groups[destination], (timestamp, self.idx))self.idx += 1return Truedef forwardPacket(self) -> List[int]:if len(self.packets) == 0:return []timestamp, idx, source, destination = self.packets.pop(0)self.seen.remove((source, destination, timestamp))self.groups[destination].pop(bisect.bisect_left(self.groups[destination], (timestamp, idx)))return [source, destination, timestamp]def getCount(self, destination: int, startTime: int, endTime: int) -> int:left = bisect.bisect_left(self.groups[destination], (startTime, -1))right = bisect.bisect_left(self.groups[destination], (endTime+1, -1))return right-left
提交代码评测得到:耗时544ms,占用内存101.5MB。