2336. Smallest Number in Infinite Set
Description of Problem
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 integernumback into the infinite set, if it is not already in the infinite set.
Example 1:
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.
Constraints:
1 <= num <= 1000- At most
1000calls will be made in total topopSmallestandaddBack.
Solution
Tags: BTree,Divide and Conquer
Explanation
Divide the data strcture into two parts: finite set (using BTree) and infinite set (using current smallest integer).
Code (Rust)
use std::collections::{BTreeSet,HashSet};
use std::cmp::Reverse;
struct SmallestInfiniteSet {
tree_in_finite : BTreeSet<i32>,
smallest_in_infinite : i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl SmallestInfiniteSet {
fn new() -> Self {
SmallestInfiniteSet {
tree_in_finite : BTreeSet::new(),
smallest_in_infinite : 1,
}
}
fn pop_smallest(&mut self) -> i32 {
if let Some(smallest) = self.tree_in_finite.pop_first() {
return smallest;
}
else{
let smallest = self.smallest_in_infinite;
self.smallest_in_infinite += 1;
return smallest;
}
}
fn add_back(&mut self, num: i32) {
if num >= self.smallest_in_infinite {
// ignore the number
}else {
// put the number into finite_part
self.tree_in_finite.insert(num);
}
}
}
/**
* Your SmallestInfiniteSet object will be instantiated and called as such:
* let obj = SmallestInfiniteSet::new();
* let ret_1: i32 = obj.pop_smallest();
* obj.add_back(num);
*/