美文网首页
Leetcode[56] Merge Intervals

Leetcode[56] Merge Intervals

作者: 耳可黄 | 来源:发表于2017-09-17 03:06 被阅读0次
Submission
/**
 * 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:
    static bool comp(Interval& a, Interval& b) {return a.start < b.start;}

    vector<Interval> merge(vector<Interval>& intervals) {
        if(intervals.empty()) return vector<Interval>();
        vector<Interval> result;
        sort(intervals.begin(), intervals.end(), comp);
        Interval last = Interval(intervals[0].start, intervals[0].end);
        for(int i = 1; i < intervals.size(); i++) {
            if(intervals[i].start <= last.end) {
                if(intervals[i].end > last.end) {
                    last.end = intervals[i].end;
                }
            } else {
                result.push_back(last);
                last.start = intervals[i].start;
                last.end = intervals[i].end;
            }
        }
        result.push_back(last);
        return result;
    }
};
Time

13ms

Explanation

First sort the array according to interval's start value in ascending order. Iterate starts at the first interval, and keep a reference of the last checked/merged interval. For each new interval, check if it should be merged; if not, add the current last interval to result.

Notes
  • c++ vector's push_back function makes a copy of the argument.
  • left reference & cannot be reassigned.

相关文章

网友评论

      本文标题:Leetcode[56] Merge Intervals

      本文链接:https://www.haomeiwen.com/subject/udhpsxtx.html