#Leetcode# 56. Merge Intervals
阿新 • • 發佈:2018-11-25
很多 ans plan back ++ urn tps val leetcode
https://leetcode.com/problems/merge-intervals/
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
代碼:
/** * 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) { if (intervals.empty()) return {}; sort(intervals.begin(), intervals.end(), [](Interval &a, Interval &b) {return a.start < b.start;}); vector<Interval> ans{intervals[0]}; for (int i = 1; i < intervals.size(); ++i) { if (ans.back().end < intervals[i].start) { ans.push_back(intervals[i]); } else { ans.back().end = max(ans.back().end, intervals[i].end); } } return ans; } };
那個 $sort$ 排序沒見過 看了題解會寫的 記上一筆!!!!總是會看到很多沒見過的有點好玩的東西 emmmm 還不是自己太菜了 o(╥﹏╥)o
#Leetcode# 56. Merge Intervals