Given a data stream input of non-negative integers a1, a2, …, an, summarize the numbers seen so far as a list of disjoint intervals.
Implement the SummaryRanges class:
SummaryRanges() Initializes the object with an empty stream.
void addNum(int value) Adds the integer value to the stream.
int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. The answer should be sorted by starti.
Example 1:
Input
[“SummaryRanges”, “addNum”, “getIntervals”, “addNum”, “getIntervals”, “addNum”, “getIntervals”, “addNum”, “getIntervals”, “addNum”, “getIntervals”]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
Output
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
Explanation
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // return [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
Constraints:
- 0 <= value <= 104
- At most 3 * 104 calls will be made to addNum and getIntervals.
维护一个数组 ranges 保存所有 range 并保证有序, add_num 的时候用 binary search 来搜索目标 range, 如果找到则更新,并检查是否需要和相邻 range 合并, 如果没有找到则插入新的 range
struct SummaryRanges {
list: Vec<(i32, i32)>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl SummaryRanges {
/** Initialize your data structure here. */
fn new() -> Self {
Self { list: Vec::new() }
}
fn add_num(&mut self, val: i32) {
if self.list.is_empty() {
self.list.push((val, val));
return;
}
let mut l = 0;
let mut r = self.list.len();
while l < r {
let m = (l + r) / 2;
if self.list[m].1 < val - 1 {
l = m + 1;
continue;
}
if self.list[m].0 == val + 1 {
self.list[m].0 = val;
if m > 0 && self.list[m - 1].1 == self.list[m].0 - 1 {
self.list[m - 1].1 = self.list[m].1;
self.list.remove(m);
}
return;
}
if self.list[m].1 == val - 1 {
self.list[m].1 = val;
if m < self.list.len() - 1 && self.list[m].1 == self.list[m + 1].0 - 1 {
self.list[m + 1].0 = self.list[m].0;
self.list.remove(m);
}
return;
}
if self.list[m].0 <= val && self.list[m].1 >= val {
return;
}
r = m;
}
if l == self.list.len() {
self.list.push((val, val));
return;
}
self.list.insert(l, (val, val));
}
fn get_intervals(&self) -> Vec<Vec<i32>> {
self.list.iter().map(|r| vec![r.0, r.1]).collect()
}
}