Leetcode 3508. Implement Router

1. 解题思路

这一题就是按照题意写作一下对应的函数即可。

我们需要注意的是,这里,定义的类当中需要包含以下一些内容:

  1. 一个所有item的集合,来快速判断当前给到的包是否已经出现过了;
  2. 一个按照时间戳以及输入顺序有序排列的所有package的队列,从而确保可以弹出最早的包;
  3. 一个按照destination进行分块,且各自按照timestamp进行有序排列的序列,从而使得可以对getCount函数进行快速实现。

2. 代码实现

给出python代码实现如下:

class Router:

    def __init__(self, memoryLimit: int):
        self.idx = 0
        self.memoryLimit = memoryLimit
        self.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 False
        if 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 += 1
        return True

    def 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值