352. Data Stream as Disjoint Intervals
https://leetcode.com/problems/data-stream-as-disjoint-intervals/
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]class SummaryRanges {
public:
map<int, int> m;
/** Initialize your data structure here. */
SummaryRanges() {
}
void addNum(int val) {
if (m.count(val)) return;
const auto r = m.upper_bound(val), l = (r == m.begin()) ? m.end() : prev(r);
if (l != m.end() && r != m.end() && l->second + 1 == val && val + 1 == r->first) {
l->second = r->second;
m.erase(r);
} else if (l != m.end() && l->second + 1 >= val) {
l->second = max(l->second, val);
} else if (r != m.end() && val + 1 == r->first) {
m[val] = r->second;
m.erase(r);
} else {
m[val] = val;
}
}
vector<vector<int>> getIntervals() {
vector<vector<int>> res;
for (const auto &p : m) {
res.push_back({p.first, p.second});
}
return res;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector<vector<int>> param_2 = obj->getIntervals();
*/Last updated