题解 | #合并区间#

合并区间

https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a?tpId=295&tqId=691&ru=%2Fpractice%2Fe297fdd8e9f543059b0b5f05f3a7f3b2&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
      std::vector<Interval> res;
      
      if (intervals.empty()) {
        return res;
      }
      
      std::sort(intervals.begin(), intervals.end(), [](Interval a, Interval b) -> bool {return a.start < b.start;});
      
      res.push_back(intervals[0]);
      
      for (int i = 1; i < intervals.size(); ++i) {
        if (intervals[i].start <= res.back().end) {
          res.back().end = std::max(res.back().end, intervals[i].end);
        } else {
          res.push_back(intervals[i]);
        }
      }
      
      return res;
    }
};
全部评论

相关推荐

12-26 14:44
复旦大学 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
12-27 22:36
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务