|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<vector<int>> merge(vector<vector<int>>& intervals) { |
| 4 | + |
| 5 | + if(intervals.size() == 0) return vector<vector<int>>(); |
| 6 | + vector<vector<int>> result; |
| 7 | + sort(intervals.begin(), intervals.end(), [](vector<int> &a, vector<int> &b){ |
| 8 | + return a[0] < b[0]; |
| 9 | + }); |
| 10 | + |
| 11 | + //sort by start of each interval |
| 12 | + //now check if end of current interval is <= start of next interval |
| 13 | + // [[1, 2], [1, 6]] ==> [here 1 in second is < end of first] !! |
| 14 | + // if current_interval_end < next_interval_start := there is overlap |
| 15 | + // set current_interval_end as max between current_end and next_end |
| 16 | + // else := no overlap |
| 17 | + // set current_interval as ith interval |
| 18 | + // add current_interval to result |
| 19 | + |
| 20 | + auto current_interval = intervals[0]; |
| 21 | + |
| 22 | + for(auto i=0; i<intervals.size(); i++) { |
| 23 | + auto current_begin = current_interval[0]; |
| 24 | + auto current_end = current_interval[1]; |
| 25 | + auto next_begin = intervals[i][0]; |
| 26 | + auto next_end = intervals[i][1]; |
| 27 | + |
| 28 | + if(next_begin <= current_end){ |
| 29 | + current_interval[1] = max(current_end, next_end); |
| 30 | + cout<<current_interval[0]<<" "<<current_interval[1]; |
| 31 | + } |
| 32 | + else { // just merge as it is.. |
| 33 | + result.push_back(current_interval); |
| 34 | + current_interval = intervals[i]; |
| 35 | + } |
| 36 | + } |
| 37 | + result.push_back(current_interval); |
| 38 | + return result; |
| 39 | + } |
| 40 | +}; |
0 commit comments