Approach
Sorting and greedy selection
For Merge2, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 29 lines of C++ from the credited upstream file merge2.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4/**5 * Definition for an interval.6 * struct Interval {7 * int start;8 * int end;9 * Interval() : start(0), end(0) {}10 * Interval(int s, int e) : start(s), end(e) {}11 * };12 */13class Solution {14 public:15 vector<Interval> merge(vector<Interval> &intervals) {16 vector<Interval> ans;17 sort(intervals.begin(), intervals.end(), 18 [](const Interval &v1, const Interval &v2) { return v1.start < v2.start; }19 );20 const int n = intervals.size();21 for(int i = 0; i < n;) {22 ans.push_back(intervals[i++]);23 while(i < n && intervals[i].start <= ans.back().end)24 ans.back().end = max(ans.back().end, intervals[i++].end);25 }26 return ans;27 }28};29