Skip to main content

56. Merge Intervals

class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals)
{
vector<vector<int>> res;

sort(intervals.begin(), intervals.end());

res.push_back(intervals[0]);

if (intervals.size() == 1) return res;

for(int i = 1; i < intervals.size(); i++)
{

if (intervals[i][0] <= res.back()[1])
{
res.back()[1] = max(res.back()[1], intervals[i][1]);
}
else
{
res.push_back(intervals[i]);
}
}
return res;
}
};
  • T: O(NN)O(N \cdot N)
  • S: O(N)O(N)