题解 | #合并区间#

合并区间

https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

/**
 * struct Interval {
 *	int start;
 *	int end;
 *	Interval(int s, int e) : start(start), end(e) {}
 * };
 */
#include <vector>
class Solution {
public:
    static bool cmp(Interval a, Interval b){
        return a.start < b.start;//表示小的排在前面
    }
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> ans;
         if(intervals.size() == 0) return ans;
        int n = intervals.size();
        sort(intervals.begin(),intervals.end(),cmp);
        ans.push_back(intervals[0]);
        for(int i = 1; i < n; i++){
            if(intervals[i].start <= ans.back().end)//当有重叠时
                ans.back().end = max(intervals[i].end, ans.back().end); //选择两元素中大的一个
            else 
               ans.push_back(intervals[i]);
        }
        return ans;
       
        
    }
};

全部评论

相关推荐

青春运维少年不会梦到...:实习大王
点赞 评论 收藏
分享
陌夏微秋:一线城市25w左右吧,17×15=255
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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