题解 | #插入区间#

插入区间

https://www.nowcoder.com/practice/1d784b5472ab4dde88ea2331d16ee909

/**
 * struct Interval {
 *	int start;
 *	int end;
 *	Interval(int s, int e) : start(start), end(e) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param Intervals Interval类vector 
     * @param newInterval Interval类 
     * @return Interval类vector
     */
    vector<Interval> insertInterval(vector<Interval>& Intervals, Interval newInterval) {
        // write code here
        vector<Interval> ans;
        if(Intervals.size()==0) {
            ans.push_back(newInterval);
            return ans;
        }
        if(Intervals.size()==1)
        {
            Interval tmp;
            tmp.start= min(Intervals[0].start,newInterval.start);
            tmp.end = max(newInterval.end,Intervals[0].end);
            ans.push_back(tmp);     
            return ans;
        }
        for(int i=0;i<Intervals.size();i++)
        {
            if(Intervals[i].end>=newInterval.start && i+1 <Intervals.size() )
            {
                if(Intervals[i+1].start<=newInterval.end )
                {
                     Interval tmp;
                    tmp.start= min(Intervals[i].start,newInterval.start);
                    while(Intervals[i].end<=newInterval.end && i+1 <Intervals.size()) i++;
                    tmp.end = max(Intervals[i].end,newInterval.end);
                    ans.push_back(tmp);                
                }
                else if(Intervals[i+1].start>newInterval.end)
                {
                     Interval tmp;
                    tmp.start= min(Intervals[i].start,newInterval.start);
                    tmp.end = newInterval.end;
                    ans.push_back(tmp);                       
                }

            }
            else ans.push_back(Intervals[i]);
        }
        return ans;
    }
};

全部评论

相关推荐

爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务