clean c++ solution


  • 0
    class Solution {
     private:
      static bool cmp(Interval& lhs, Interval& rhs) {
        if (lhs.start != rhs.start) return lhs.start < rhs.start;
        return lhs.end < rhs.end;
      }
    
      vector<Interval> merge(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), cmp);
    
        vector<Interval> ans;
        for (auto it : intervals) {
          if (ans.empty())
            ans.push_back(it);
          else {
            if (it.start <= ans.back().end)
              ans.back().end = max(it.end, ans.back().end);
            else
              ans.push_back(it);
          }
        }
        return ans;
      }
    
     public:
      vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        intervals.push_back(newInterval);
        return merge(intervals);
      }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.