
class Solution {
public:
vector<Interval> merge(vector<Interval>& vec) {
if (vec.empty() || vec.size() == 1)
return vec;
sort(vec.begin(), vec.end(), [](Interval a, Interval b) -> bool { return a.start < b.start; });
Interval tep;
tep.start = 0;
tep.end = 0;
stack<int>sta;
sta.push(vec[0].start);
sta.push(vec[0].end);
for (int i = 1; i < vec.size(); i++) {
if (sta.top() >= vec[i].start) {
int t1 = sta.top();
sta.pop();
int t0 = sta.top();
sta.pop();
if (t0 <= vec[i].start) {
t1 = max(t1, vec[i].end);
sta.push(t0);
sta.push(t1);
}
}else{
sta.push(vec[i].start);
sta.push(vec[i].end);
}
}
tep.start = 0;
tep.end = 0;
vector<Interval>res = vector<Interval>(sta.size()/2, tep);
int index = res.size() - 1;
while (!sta.empty()) {
if (sta.size() % 2 == 0) {
tep.end = sta.top();
sta.pop();
} else {
tep.start = sta.top();
sta.pop();
}
if (sta.size() % 2 == 0){
res[index] = tep;
index--;
}
}
return res;
}
};