[LeetCode] Smallest Number in Infinite Set

2336. Smallest Number in Infinite Set

You have a set which contains all positive integers [1, 2, 3, 4, 5, …].

Implement the SmallestInfiniteSet class:

  • SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.
  • int popSmallest() Removes and returns the smallest integer contained in the infinite set.
  • void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class SmallestInfiniteSet {
int mi = 1;
set<int> st;
public:
SmallestInfiniteSet() {}

int popSmallest() {
if(st.empty()) return mi++;
int res = *begin(st);
st.erase(begin(st));
return res;
}

void addBack(int num) {
if(mi <= num) return;
st.insert(num);
}
};

/**
* Your SmallestInfiniteSet object will be instantiated and called as such:
* SmallestInfiniteSet* obj = new SmallestInfiniteSet();
* int param_1 = obj->popSmallest();
* obj->addBack(num);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/10/PS/LeetCode/smallest-number-in-infinite-set/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.