LeetCode: Merge Intervals

来源:互联网 发布:周杰伦 四面楚歌 知乎 编辑:程序博客网 时间:2024/05/01 12:04

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

类里的比较函数貌似只能这么写。

struct myclass {  bool operator() (int i,int j) { return (i<j);}} myobject;



/** * 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> merge(vector<Interval> &intervals) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        sort(intervals.begin(), intervals.end(), myobject);        vector<Interval> res;        int nSize = intervals.size();        if(nSize < 2){            return intervals;        }        Interval cur = intervals[0];        for(int i = 1; i< nSize; ++i){            Interval &t = intervals[i];            if(cur.end < t.start){                res.push_back(cur);                cur = intervals[i];            }            else{                cur.end = cur.end > t.end ? cur.end : t.end;            }        }        res.push_back(cur);        return res;    }    struct myclass {        bool operator() (const Interval &a, const Interval &b){        return a.start < b.start;        }    } myobject;    };


原创粉丝点击