码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Solution-56

时间:2020-01-30 21:10:18      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:NPU   out   添加   ide   区间   inter   runtime   back   merge   

56: 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.

思路:
将区间的左端点按从小到大进行排序,然后观察相邻2个区间是否有公共部分,如果有公共部分则选取右端点的最大值作为新的区间的右端点,如果无公共部分则直接添加新区间。

Solution:

vector<vector<int>> merge(vector<vector<int>>& intervals) {
    if (intervals.empty()) return vector<vector<int>>{};
        
    vector<vector<int>> res;
    sort(intervals.begin(), intervals.end(), [] (vector<int> a, vector<int> b) {return a.front() < b.front();});
    res.push_back(intervals[0]);
    for (int i = 1; i < intervals.size(); i++) {
        if (res.back().back() < intervals[i].front()) res.push_back(intervals[i]);
        else
            res.back().back() = max (res.back().back(), intervals[i].back());
    }
    return res;
}

性能:
Runtime: 80 ms??Memory Usage: 26.5 MB

LeetCode Solution-56

标签:NPU   out   添加   ide   区间   inter   runtime   back   merge   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12243710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!