Given an array of non-negative integers, you are initially positioned at the first index of the array.
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]
.
给定若干区间,把存在重叠的区间合并
1. 先对区间按开始值一级升序排列,然后按照结束值二级升序排列
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool compare(const Interval&o1, const Interval&o2){ if(o1.start<o2.start)return true; else if(o1.start==o2.start){ return o1.end<o2.end; } return false; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> result; int size=intervals.size(); if(size==0)return result; //排序 sort(intervals.begin(), intervals.end(),compare); //合并 Interval curInterval(intervals[0].start, intervals[0].end); for(int i=1; i<size; i++){ if(curInterval.end<intervals[i].start){ result.push_back(curInterval); curInterval=Interval(intervals[i].start, intervals[i].end); } else{ if(intervals[i].end>curInterval.end)curInterval.end=intervals[i].end; } } //别忘了最后一个区间 result.push_back(curInterval); return result; } };
LeetCode: Merge Intervals [055],布布扣,bubuko.com
LeetCode: Merge Intervals [055]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26744153