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