Skip to content

Commit 212b69a

Browse files
authored
Create Smallest Number in Infinite Set.java
1 parent 98e96c0 commit 212b69a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Smallest Number in Infinite Set.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// https://leetcode.com/problems/smallest-number-in-infinite-set/
2+
3+
class SmallestInfiniteSet {
4+
5+
// Create a TreeSet and a variable to hold the smallest number
6+
// NOTE: TreeSet is a self-balancing BST - similar to a Red-Black tree
7+
TreeSet<Integer> set;
8+
int smallestNum;
9+
10+
public SmallestInfiniteSet() {
11+
12+
// Initialize class variables
13+
set = new TreeSet<>();
14+
smallestNum = 1;
15+
}
16+
17+
public int popSmallest() {
18+
19+
// OBJECTIVE: Pop smallest element from set or return smallestNum
20+
21+
// If tree isn't empty, pop head element
22+
if (!set.isEmpty()) {
23+
return set.pollFirst();
24+
}
25+
26+
// If tree is empty, return smallest number based on variable
27+
smallestNum++;
28+
return smallestNum - 1;
29+
}
30+
31+
public void addBack(int num) {
32+
33+
// OBJECTIVE: Add num to tree if it doesn't exist
34+
35+
// If num is less than smallestNum and doesn't exist in set, add it to set
36+
if (num < smallestNum && !set.contains(num)) {
37+
set.add(num);
38+
}
39+
}
40+
}
41+
42+
/**
43+
* Your SmallestInfiniteSet object will be instantiated and called as such:
44+
* SmallestInfiniteSet obj = new SmallestInfiniteSet();
45+
* int param_1 = obj.popSmallest();
46+
* obj.addBack(num);
47+
*/

0 commit comments

Comments
 (0)