美文网首页Leetcode
Leetcode 57. Insert Interval

Leetcode 57. Insert Interval

作者: SnailTyan | 来源:发表于2018-12-08 18:51 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Insert Interval

    2. Solution

    /**
     * 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> insert(vector<Interval>& intervals, Interval newInterval) {
            vector<Interval> result;
            int i = 0;
            bool inserted = false;
            for(i = 0; i < intervals.size(); i++) {
                Interval current = intervals[i];
                if(current.end < newInterval.start) {
                    result.push_back(current);
                }
                else if(newInterval.end < current.start) {
                    result.push_back(newInterval);
                    inserted = true;
                    break;
                }
                else {
                    newInterval.start = min(current.start, newInterval.start);
                    newInterval.end = max(current.end, newInterval.end);
                }
            }
            if(!inserted) {
                result.push_back(newInterval);
            }
            for(i = i; i < intervals.size(); i++) {
                result.push_back(intervals[i]);
            }
            return result;
        }
    };
    

    Reference

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

    相关文章

      网友评论

        本文标题:Leetcode 57. Insert Interval

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