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

56. Merge Intervals (Array; Project)

时间:2015-12-05 11:07:06      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        if(intervals.empty() || intervals.size() == 1) return intervals;
        for(vector<Interval>::iterator it = intervals.begin()+1; it < intervals.end();it++)
        {
            for(vector<Interval>::iterator innerIt = intervals.begin(); innerIt < it;innerIt++)
            {
                int left = min(it->start, innerIt->start);
                int right = max(it->end, innerIt->end);
                int size1 = (it->end) - (it->start);
                int size2 = (innerIt->end) - (innerIt->start);
                if(right - left > size1 + size2) //求线段是否重叠:比较投影的左右端点间长度与线段长度和
                    continue;
                else
                {
                    innerIt->start = left;
                    innerIt->end = right;
                    intervals.erase(it);
                    it = innerIt;
                    break;
                }
            }
        }
        return intervals;
    }
};

 

56. Merge Intervals (Array; Project)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/5021123.html

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