当前位置:网站首页>LeetCode 2336. 无限集中的最小数字(SortedSet)
LeetCode 2336. 无限集中的最小数字(SortedSet)
2022-08-02 17:48:00 【Michael阿明】
1. 题目
现有一个包含所有正整数的集合 [1, 2, 3, 4, 5, …] 。
实现 SmallestInfiniteSet 类:
SmallestInfiniteSet()初始化SmallestInfiniteSet对象以包含 所有 正整数。int popSmallest()移除 并返回该无限集中的最小整数。void addBack(int num)如果正整数 num 不 存在于无限集中,则将一个 num 添加 到该无限集中。
示例:
输入
["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]
[[], [2], [], [], [], [1], [], [], []]
输出
[null, null, 1, 2, 3, null, 1, 4, 5]
解释
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.addBack(2); // 2 已经在集合中,所以不做任何变更。
smallestInfiniteSet.popSmallest(); // 返回 1 ,因为 1 是最小的整数,并将其从集合中移除。
smallestInfiniteSet.popSmallest(); // 返回 2 ,并将其从集合中移除。
smallestInfiniteSet.popSmallest(); // 返回 3 ,并将其从集合中移除。
smallestInfiniteSet.addBack(1); // 将 1 添加到该集合中。
smallestInfiniteSet.popSmallest(); // 返回 1 ,因为 1 在上一步中被添加到集合中,
// 且 1 是最小的整数,并将其从集合中移除。
smallestInfiniteSet.popSmallest(); // 返回 4 ,并将其从集合中移除。
smallestInfiniteSet.popSmallest(); // 返回 5 ,并将其从集合中移除。
提示:
1 <= num <= 1000
最多调用 popSmallest 和 addBack 方法 共计 1000 次
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/smallest-number-in-infinite-set
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 使用有序set,插入数据后会自动排序
from sortedcontainers import SortedSet
class SmallestInfiniteSet:
def __init__(self):
self.s = SortedSet(range(1, 1001))
def popSmallest(self) -> int:
return self.s.pop(0)
def addBack(self, num: int) -> None:
self.s.add(num)
232 ms 16.3 MB Python3
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
边栏推荐
- IDEA相关配置(特别完整)看完此篇就将所有的IDEA的相关配置都配置好了、设置鼠标滚轮修改字体大小、设置鼠标悬浮提示、设置主题、设置窗体及菜单的字体及字体大小、设置编辑区主题、通过插件更换主题
- ES: Promise的基本用法
- Interviewer: can you talk about optimistic locking and pessimistic locks
- 记一次 .NET 某工控自动化控制系统 卡死分析
- 基于HDF的LED驱动程序开发(1)
- 解决多版本jar包冲突问题
- NeRF: The Secret of 3D Reconstruction Technology in the Popular Scientific Research Circle
- 在线文档Sheet技术解析
- golang刷leetcode 经典(6) 实现跳表
- 二叉查找树的查找
猜你喜欢
随机推荐
Redis总结_实战篇
Smart Microelectronics Releases Low-Power MM32L0130 Series MCU Products
谁抢走了华大基因的生意?
Wechat Gymnasium Appointment Mini Program Graduation Design Finished Work (5) Task Book
面试官:可以谈谈乐观锁和悲观锁吗
POE交换机全方位解读(下)
How to ensure the security of smart factories?
golang学习之七:并发编程基础(goroutine、channel、select)
golang刷leetcode 经典(5)设计哈希集合
脉脉上的相亲生意
动力电池扩产潮,宁德时代遭围剿
Ubuntu系统下用docker安装oracle
玩转云端 | 天翼云对象存储ZOS高可用的关键技术揭秘
ES: WeakSet
The days of patching are more difficult than the days of writing code
发挥云网融合优势,天翼云为政企铺设数字化转型跑道
灵动微电子发布低功耗 MM32L0130 系列 MCU 产品
判断文件属主
牛津硕士进碳圈,高瓴红杉经纬一起投了
如何应对机器身份带来的安全风险









![Open Source Summer | [Cloud Native] DevOps (5): Integrating Harbor](/img/db/16ae82217382e72824a4b454060833.png)