Created
May 3, 2020 18:18
-
-
Save AnthonyMikh/828b7f54f14a4ce905eaf06fcdf19d5e to your computer and use it in GitHub Desktop.
Solution to "Data Stream as Disjoint Intervals" Leetcode problem
This file contains hidden or 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
| use std::cell::Cell; | |
| use std::collections::BTreeMap; | |
| struct SummaryRanges { | |
| ranges: BTreeMap<Cell<i32>, i32>, | |
| } | |
| impl SummaryRanges { | |
| fn new() -> Self { | |
| Self { ranges: BTreeMap::new() } | |
| } | |
| fn add_num(&mut self, val: i32) { | |
| let mut iter = self.ranges.iter_mut(); | |
| let adjoint = iter.by_ref() | |
| .find(|(start, end)| { | |
| let start = start.get().saturating_sub(1); | |
| let end = end.saturating_add(1); | |
| (start..=end).contains(&val) | |
| }); | |
| let (start, end) = match adjoint { | |
| None => { | |
| self.ranges.insert(Cell::new(val), val); | |
| return; | |
| }, | |
| Some(range) => range, | |
| }; | |
| if val < start.get() { // val is just before start | |
| start.set(val); | |
| return; | |
| } | |
| if val <= *end { | |
| // val is within range, there is nothing to do | |
| return; | |
| } | |
| *end = val; | |
| let next = match iter.next() { | |
| None => return, | |
| Some(next) => next, | |
| }; | |
| if next.0.get() == *end + 1 { | |
| *end = *next.1; | |
| let to_remove = next.0.clone(); | |
| self.ranges.remove(&to_remove); | |
| } | |
| } | |
| fn get_intervals(&self) -> Vec<Vec<i32>> { | |
| self.ranges.iter() | |
| .map(|(start, &end)| vec![start.get(), end]) | |
| .collect() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment