Leetcode题目:
不断地添加区间到区间集合中,并计算出现在至少一个区间中的整数个数。
使用BTreemap动态开区间。
use std::collections::BTreeMap;
struct CountIntervals {
mp: BTreeMap<i32, i32>,
cnt: i32,
}
impl CountIntervals {
fn new() -> Self {
CountIntervals {
mp: BTreeMap::new(),
cnt: 0,
}
}
fn add(&mut self, mut left: i32, mut right: i32) {
let mut interval_index = self.mp.range(..=right).next_back();
while let Some((&l, &r)) = interval_index {
if l > right || r < left {
break;
}
left = left.min(l);
right = right.max(r);
self.cnt -= r - l + 1;
self.mp.remove(&l);
interval_index = self.mp.range(..=right).next_back();
}
self.cnt += right - left + 1;
self.mp.insert(left, right);
}
fn count(&self) -> i32 {
self.cnt
}
}
标签:mut,cnt,right,self,个数,添加,mp,区间,left
From: https://www.cnblogs.com/mariocanfly/p/18089395