当前位置: 首页 > news >正文

Leetcode 3508. Implement Router

  • Leetcode 3508. Implement Router
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接: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。

相关文章:

  • Java数据结构的基础用法
  • 嵌入式AI开源生态指南:从框架到应用的全面解析
  • JavaScript学习教程,从入门到精通,JavaScript 基础语法全面指南(5)
  • 2025.4.6总结
  • 低空经济基础设施建设方向与展望
  • 深入详解流形学习中的几何解释
  • 机器学习/深度学习
  • HTML语言的数据可视化
  • deepseek为采用JAVA重构模型运营平台vLLM和SGLang指定的计划
  • 【学习笔记】Ruckig: 高效实时运动规划库
  • 如何获取oracle cloud永久免费的vps(4C/24G)?
  • 机器学习的一百个概念(10)假阳性率
  • Spring 中的 bean 生命周期
  • 数据对象:DTO、DO、PO和 BO的区别和关系
  • 用 C++ 写汉诺塔程序
  • 从零开始的编程-java篇1.6.3
  • 医院大数据处理的主要痛点分析
  • 低代码开发平台:飞帆制作网页并集成到自己的网页中
  • 1110+款专业网站应用程序UI界面设计矢量图标figma格式素材 Icon System | 1,100+ Icons Easily Customize
  • FreeRTOS移植笔记:让操作系统在你的硬件上跑起来
  • 微网站用手机可以做吗/腾讯云建站
  • win2003做网站/百度一下马上知道
  • 精美网站建设/百度seo优化怎么做
  • cnd中国室内设计网/西安seo服务公司排名
  • 3d云打印网站开发/百度今日数据统计
  • 河北省建设工程安全生产监督管理网站/百度一下你就知道百度一下