1. 程式人生 > >leetcode || 56、 Merge Intervals

leetcode || 56、 Merge Intervals

題意 als push_back air snippet ast ret cor anim

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