首页 > 代码库 > leetcode || 56、 Merge Intervals

leetcode || 56、 Merge Intervals

problem:

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

Hide Tags
 Array Sort
题意:给定数组区间,合并有覆盖或者相邻的区间

thinking:

(1)一開始我想到用hash table的方法,开一个总区间跨度的数组。对于有区间覆盖的数组区间置为true。没被覆盖的数组区间置为false,最后将true区间的起点和终点作为区间输出就可以。

思路简单。可是,我忽略一个问题:区间跨度是不定的,所以要开的数组大小有可能非常大。提交也显示:Memory Limit Exceeded

(2)换一种方法。排序法。

能够直接对vector<Interval> 数组排序,要重载compare函数。也能够使用multimap<int, int>,注意不是map


code:

排序法: Accepted

class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> ret;
        multimap<int,int> map_intervals;
        if(intervals.size()==0)
            return ret;
        if(intervals.size()==1)
            return intervals;
        for(vector<Interval>::iterator it=intervals.begin();it!=intervals.end();it++)
            map_intervals.insert(make_pair((*it).start,(*it).end));
        multimap<int, int>::iterator p=map_intervals.begin();
        Interval tmp(p->first,p->second);
        for(multimap<int, int>::iterator k=++p;k!=map_intervals.end();k++)
        {
            if(k->first<=tmp.end)
                tmp.end=max(tmp.end,k->second);
            else
            {
                ret.push_back(tmp);
                tmp.start=k->first;
                tmp.end=k->second;
            }
        }
        ret.push_back(tmp);
        return ret;
    }
};
hash table 法:Memory Limit Exceeded

class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> ret;
        int first=INT_MAX, last=INT_MIN;
        for(vector<Interval>::iterator tmp=intervals.begin();tmp!=intervals.end();tmp++)
        {
            first=min((*tmp).start,first);
            last=max((*tmp).end,last);
        }
        int count=last-first+1;
        bool *a = new bool[count];
        memset(a,false,sizeof(bool)*count);
        for(vector<Interval>::iterator it=intervals.begin();it!=intervals.end();it++)
        {
            int num=(*it).end-(*it).start+1;
            memset(a+(*it).start,true,sizeof(bool)*num);
        }
        int interval_start=0,interval_end=0;
        while(interval_end<count)
        {
            interval_end=interval_start;
            int index=0;
            while(interval_start+index<count && a[index])
                index++;
            interval_end+=index-1;
            Interval tmp_interval(interval_start,interval_end);
            ret.push_back(tmp_interval);
            if(interval_end<count)
            {
                int loc =interval_end+1;
                while(loc<count && (!a[loc]))
                    loc++;
                interval_start=loc;
            }
        }

    }
};


leetcode || 56、 Merge Intervals