Leetcode 352 Solution
This article provides solution to leetcode question 352 (data-stream-as-disjoint-intervals)
Access this page by simply typing in "lcs 352" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/data-stream-as-disjoint-intervals
Solution
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
struct Interval_comparator
{
bool operator() (const Interval& i1, const Interval& i2)
{
return i1.start < i2.start || (i1.start == i2.start && i1.end < i2.end);
}
};
class SummaryRanges {
set<Interval, Interval_comparator> intervals;
public:
/** Initialize your data structure here. */
SummaryRanges() {
}
void addNum(int val) {
auto it = intervals.find(Interval(val, val));
if (it != intervals.end())
return;
intervals.insert(Interval(val, val));
it = intervals.find(Interval(val, val));
if (it != intervals.begin())
{
auto left_it = it;
left_it--;
if (left_it->end + 1 == it->start)
{
int new_start = left_it->start;
int new_end = it->end;
intervals.erase(left_it);
intervals.erase(it);
intervals.insert(Interval(new_start, new_end));
it = intervals.find(Interval(new_start, new_end));
}
else if (left_it->end >= it->start)
{
intervals.erase(it);
return;
}
}
auto right_it = it;
right_it++;
if (right_it != intervals.end())
{
if (right_it->start == it->end + 1)
{
int new_start = it->start;
int new_end = right_it->end;
intervals.erase(right_it);
intervals.erase(it);
intervals.insert(Interval(new_start, new_end));
it = intervals.find(Interval(new_start, new_end));
}
else if (right_it->start <= it->end)
{
intervals.erase(it);
return;
}
}
}
vector<Interval> getIntervals() {
vector<Interval> res;
for (auto interval : intervals)
res.push_back(interval);
return res;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* vector<Interval> param_2 = obj.getIntervals();
*/