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

60. Insert Interval && Merge Intervals

时间:2014-09-09 10:29:58      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   strong   for   art   div   cti   

Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

思路: 因为区间按 start 升序,且无重叠。所以插入区间和每一个元素分三种情况考虑。在左边,在右边(此两种情况直接拿区间出来)或者交叉(则更新插入区间范围)。 利用变量 out 判断新的区间是否已经放入。

/**
 * 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:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        vector<Interval> vec;
        bool out = true;
        for(size_t i = 0; i < intervals.size(); ++i) {
            if(intervals[i].end < newInterval.start) {
                vec.push_back(intervals[i]);
            } else if(intervals[i].start > newInterval.end) {
                if(out) { vec.push_back(newInterval); out = false;}
                vec.push_back(intervals[i]);
            } else {
                newInterval.start = min(newInterval.start, intervals[i].start);
                newInterval.end = max(newInterval.end, intervals[i].end);
            }
        }
        if(out) 
            vec.push_back(newInterval); 
        return vec;
    }
};

 

Merge Intervals

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].

思路: 先按 start 排序。然后,判断当前区间和前一区间是否重叠。若没重叠,则放入;若重叠,则更新前一区间 end, 舍弃当前区间。

/**
 * 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 cmp(Interval a, Interval b) {
    return a.start < b.start;
}
class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        sort(intervals.begin(), intervals.end(), cmp);
        vector<Interval> vec;
        for(size_t i = 0; i < intervals.size(); ++i) {
            if(vec.empty()) vec.push_back(intervals[i]);
            else if(intervals[i].start <= vec.back().end)
                vec.back().end = max(intervals[i].end, vec.back().end);
            else vec.push_back(intervals[i]);
        }
        return vec;
    }
};

 

60. Insert Interval && Merge Intervals

标签:style   blog   io   ar   strong   for   art   div   cti   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3961177.html

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