-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathSmallest Number in Infinite Set.cpp
60 lines (39 loc) · 1.25 KB
/
Smallest Number in Infinite Set.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Solution By Rahul Surana
***********************************
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.
*************************************/
#include<bits/stdc++.h>
class SmallestInfiniteSet {
public:
int i = 1;
set<int> s;
SmallestInfiniteSet() {
}
int popSmallest() {
if(s.size() == 0){
return i++;
}
else{
int a = *s.begin();
if(i > a){
s.erase(a);
return a;
}
return i++;
}
}
void addBack(int num) {
if(i > num) s.insert(num);
}
};
/**
* Your SmallestInfiniteSet object will be instantiated and called as such:
* SmallestInfiniteSet* obj = new SmallestInfiniteSet();
* int param_1 = obj->popSmallest();
* obj->addBack(num);
*/