*Leetcode 57. Insert Interval

https://leetcode.com/problems/insert-interval/description/

应该是一道比较简单的hard题了

可能考的是对api的熟悉程度,不会api的比如我,就是排序在合并了

 bool cmp(const Interval a, const Interval b) {
        if (a.start != b.start) return a.start < b.start;
        return a.end < b.end;
    }
class Solution {
public:

    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        vector<Interval> ret;
        intervals.push_back(newInterval);
        // if (intervals.size() == 0) return ret;
        
        if (intervals.size() == 1) return intervals;
        sort(intervals.begin(), intervals.end(), cmp);
        Interval last = intervals[0];
        for(int i = 1; i < intervals.size(); i++) {
            if (last.end < intervals[i].start) { // no inter
                    ret.push_back(last);
                    last = intervals[i];
                } else {
                    last.start = min(last.start, intervals[i].start);
                    last.end = max(last.end, intervals[i].end);
                }
            if (i == intervals.size() - 1) {
                ret.push_back(last);
            }
        }
        
        return ret;
    }
};

然后写的比较漂亮的一个solution

https://leetcode.com/problems/insert-interval/discuss/21599/

class Solution {
public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        auto compare = [] (const Interval &intv1, const Interval &intv2)
                          { return intv1.end < intv2.start; };
        auto range = equal_range(intervals.begin(), intervals.end(), newInterval, compare);
        auto itr1 = range.first, itr2 = range.second;
        if (itr1 == itr2) {
            intervals.insert(itr1, newInterval);
        } else {
            itr2--;
            itr2->start = min(newInterval.start, itr1->start);
            itr2->end = max(newInterval.end, itr2->end);
            intervals.erase(itr1, itr2);
        }
        return intervals;
    }
};
相关文章
相关标签/搜索