题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
算是暴力通过的吧,思路和前边的题目是差不多的
还是新建一个tempgp数组,用来存放新的区间数组元素
就是Debug有点头疼
有个小的bug,这里 static bool cmp
要记得在前面加上static,不然会错
https://blog.csdn.net/weixin_40710708/article/details/111269356
/**
* 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:
static bool cmp(Interval a, Interval b) {
return a.start < b.start;
}
vector<Interval> merge(vector<Interval> &intervals) {
int size = intervals.size();
if(size == 0) return intervals;
sort(intervals.begin(), intervals.end(), cmp);
vector<Interval> tempgp;
tempgp.push_back(intervals[0]);
for(int i = 1; i < size; i++) {
int length = tempgp.size();
if(tempgp[length - 1].end >= intervals[i].start && tempgp[length - 1].end >= intervals[i].end) {
continue;
}
else if(tempgp[length - 1].end >= intervals[i].start && tempgp[length - 1].end < intervals[i].end) {
tempgp[length - 1].end = intervals[i].end;
}
else {
Interval temp;
temp.start = intervals[i].start;
temp.end = intervals[i].end;
tempgp.push_back(temp);
}
}
return tempgp;
}
};