Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2023-04-25 17:40:24
2336. Smallest Number in Infinite Set
设计一个资料结构,这个资料结构有是一个集合且元素数量有无限个,实作:
- SmallestInfiniteSet():初始化类别,集合一开始有无限个元素。
- int popSmallest(): 从集合移除最小元素并返回。
- void addBack(int num):加入一个元素,如果元素已经在集合则忽略。
Example:
Input
["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest",
"popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]
[[], [2], [], [], [], [1], [], [], []]
Output
[null, null, 1, 2, 3, null, 1, 4, 5]
Explanation
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.addBack(2); // 2 is already in the set, so no change
is made.
smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest
number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.
smallestInfiniteSet.addBack(1); // 1 is added back to the set.
smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the
set and
// is the smallest number, and remove it
from the set.
smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.
思路:
1.用一个heap保存顶端最小元素,一个Set保存集合里面是否包含重复值。
2.加入元素操作,下列情况之一不做处理:
* 要加入的元素大小高于于pop的数量,表示这个元素已存在没被移除过。
* 元素不存在Set之中。
如果上面两个都不满足则把当前元素加入heap。
3.取出元素操作,如果set为空表示最顶端元素是count,返回count并加一
如果set不为空表示有元素被重新加入,从heap之中取顶端(最小)值。
Java Code:
作者: PogChampLUL (火车站肥宅)   2023-04-25 17:45:00
大师
作者: Che31128 (justjoke)   2023-04-25 17:45:00
:000大师
作者: JIWP (JIWP)   2023-04-25 17:47:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com