首页 > 代码库 > Leetcode--Merge Intervals
Leetcode--Merge Intervals
Problem Description:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ struct cmpLess { bool operator ()(const Interval & a,const Interval & b) { return a.start<b.start; } }; class Solution { public: Interval merge(Interval a,Interval b) { Interval c; c.start=min(a.start,b.start); c.end=max(a.end,b.end); return c; } vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> res; if(intervals.size()==0) return res; Interval temp; int flag=0;//判断上一次是否有区间合并 sort(intervals.begin(),intervals.end(),cmpLess()); for(int i=1;i<intervals.size();i++) { if(flag==0) { if(intervals[i-1].end<intervals[i].start) res.push_back(intervals[i-1]); else { temp=merge(intervals[i-1],intervals[i]); flag=1; } } else { if(temp.end<intervals[i].start) { res.push_back(temp); flag=0; } else temp=merge(temp,intervals[i]); } } if(flag==0) res.push_back(intervals[intervals.size()-1]); else res.push_back(temp); return res; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。