352. Data Stream as Disjoint Intervals
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
[1, 1] [1, 1], [3, 3] [1, 1], [3, 3], [7, 7] [1, 3], [7, 7] [1, 3], [6, 7]
Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?
Rust Solution
use std::collections::BTreeMap;
use std::collections::HashSet;
struct SummaryRanges {
data: BTreeMap<i32, i32>,
seen: HashSet<i32>,
}
impl SummaryRanges {
fn new() -> Self {
let data = BTreeMap::new();
let seen = HashSet::new();
SummaryRanges { data, seen }
}
fn add_num(&mut self, val: i32) {
if !self.seen.insert(val) {
return;
}
let mut l = val;
let mut r = val;
if let Some(&right) = self.data.get(&(val + 1)) {
r = right;
}
if let Some((&left, &limit)) = self.data.range(..val).rev().next() {
if limit == val - 1 {
l = left;
}
}
if l < val {
self.data.remove(&l);
}
if r > val {
self.data.remove(&(val + 1));
}
self.data.insert(l, r);
}
fn get_intervals(&self) -> Vec<Vec<i32>> {
self.data.iter().map(|(&k, &v)| vec![k, v]).collect()
}
}
#[test]
fn test() {
let mut obj = SummaryRanges::new();
obj.add_num(1);
obj.add_num(3);
obj.add_num(7);
obj.add_num(2);
obj.add_num(6);
assert_eq!(obj.get_intervals(), vec![vec![1, 3], vec![6, 7]]);
}
Having problems with this solution? Click here to submit an issue on github.