leetcode--Merge Intervals

1.题目描述

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

2.解法分析

题目很简单。只是自定义的排序仿函数要放在solution类外面,否则会出现如下错误:

Line 23: no matching function for call to 'sort(std::vector<Interval>::iterator, std::vector<Interval>::iterator, <unresolved overloaded function type>)'
代码如下:
/**
 * 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 lc(const Interval &a,const Interval &b)
{
    return a.start<b.start;
}
 
class Solution {
public:
 
 
    vector<Interval> merge(vector<Interval> &intervals) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<Interval>result;
        if(intervals.empty())return result;
        
        std::sort(intervals.begin(),intervals.end(),lc);
        Interval cur=intervals[0];
        
        int len=intervals.size();
        if(len==1)return intervals;
        
        int i=1;
        while(i<len)
        {
            if(cur.end>=intervals[i].start)
            {
                cur.end=max(intervals[i].end,cur.end);
            }
            
            else
            {
                result.push_back(cur);
                cur=intervals[i];
            }
            i++;
        }
        
        if(result.empty()||result.back().end<cur.start)result.push_back(cur);
        return result;
        
        
        
        
    }
    
};
posted @ 2013-08-27 00:45  曾见绝美的阳光  阅读(556)  评论(0编辑  收藏  举报