56. Merge Intervals
Posted The Tech Road
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了56. Merge Intervals相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/merge-intervals/description/
/** * 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) { auto comp = [](const Interval& i1, const Interval& i2) { return i1.start < i2.start || i1.start == i2.start && i1.end < i2.end; }; sort(intervals.begin(), intervals.end(), comp); vector<Interval> res; if (intervals.empty()) return res; Interval cur = intervals[0]; for (int i = 1; i < intervals.size(); i++) { if (intervals[i].start <= cur.end) { cur.end = max(cur.end, intervals[i].end); } else { res.push_back(cur); cur = intervals[i]; } } res.push_back(cur); return res; } };
以上是关于56. Merge Intervals的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 56. Merge Intervals