-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2336: Smallest Number in Infinite Set
- Loading branch information
Showing
3 changed files
with
908 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
84 changes: 84 additions & 0 deletions
84
src/problem_2336_smallest_number_in_infinite_set/binary_heap.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
use std::cmp::{Ordering, Reverse}; | ||
use std::collections::{BinaryHeap, HashSet}; | ||
|
||
pub struct SmallestInfiniteSet { | ||
front: BinaryHeap<Reverse<u32>>, | ||
front_values: HashSet<u32>, | ||
back: u32, | ||
} | ||
|
||
impl SmallestInfiniteSet { | ||
fn new() -> Self { | ||
Self { | ||
front: BinaryHeap::new(), | ||
front_values: HashSet::new(), | ||
back: 0, | ||
} | ||
} | ||
|
||
fn pop_smallest(&mut self) -> i32 { | ||
if let Some(Reverse(value)) = self.front.pop() { | ||
if value < self.back { | ||
self.front_values.remove(&value); | ||
|
||
return value as _; | ||
} | ||
|
||
self.front.clear(); | ||
} | ||
|
||
self.back += 1; | ||
|
||
self.back as _ | ||
} | ||
|
||
fn add_back(&mut self, num: i32) { | ||
let num = num as u32; | ||
|
||
match num.cmp(&self.back) { | ||
Ordering::Less => { | ||
if self.front_values.insert(num) { | ||
self.front.push(Reverse(num)); | ||
} | ||
} | ||
Ordering::Equal => { | ||
self.front_values.remove(&num); | ||
|
||
loop { | ||
self.back -= 1; | ||
|
||
if !self.front_values.remove(&self.back) { | ||
break; | ||
} | ||
} | ||
} | ||
Ordering::Greater => {} | ||
} | ||
} | ||
} | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl super::SmallestInfiniteSet for SmallestInfiniteSet { | ||
fn new() -> Self { | ||
Self::new() | ||
} | ||
|
||
fn pop_smallest(&mut self) -> i32 { | ||
self.pop_smallest() | ||
} | ||
|
||
fn add_back(&mut self, num: i32) { | ||
self.add_back(num); | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
#[test] | ||
fn test_solution() { | ||
super::super::tests::run::<super::SmallestInfiniteSet>(); | ||
} | ||
} |
Oops, something went wrong.