leetcode: sort interval

key1: check vector  is empty

key2: sort vector

key3: vector has functon of  vector.back() // get the last element;

 static bool cmp(Interval a, Interval b){
        if(a.start == b.start)
            return a.end < b.end;
        else{
            return a.start < b.start;
        }
    }
    vector<Interval> merge(vector<Interval> &intervals) {
        int len = intervals.size();
        if(len == 0) return vector<Interval>{};
        sort(intervals.begin(), intervals.end(),cmp);
        vector<Interval> res;
        res.push_back(intervals[0]);
        for (int i = 1; i < intervals.size(); i++) {
        if (res.back().end < intervals[i].start) res.push_back(intervals[i]);
        else
            res.back().end = max(res.back().end, intervals[i].end);
        }
        return res;
    }

 

点赞