码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 57. Insert Interval

时间:2016-08-04 10:27:23      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

57. Insert Interval

  • Total Accepted: 64309
  • Total Submissions: 260619
  • Difficulty: Hard

 

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

 

 

思路:区间划分。先找到新区间的左边界,再找到新区间的右边界。画图会更加清晰。

左边界:不满足intervals[i].end<newInterval.start意味着intervals[i-1].end<newInterval.start<=intervals[i].end。

右边界:满足intervals[j].start<newInterval.end时,不断合并区间,将intervals[j]和newInterval合并为新的newInterval,再尝试和intervals[j+1]合并,直到不能合并。因为intervals[j]和intervals[j+1]是区间独立的,所以intervals[j]被合并不会影响intervals[j+1]。

 

代码:

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
13         int i,j;
14         vector<Interval> res;
15         for(i=0;i<intervals.size()&&intervals[i].end<newInterval.start;i++){//i
16             res.push_back(intervals[i]);
17         }
18         for(j=i;j<intervals.size()&&intervals[j].start<=newInterval.end;j++){
19             newInterval=Interval(min(intervals[j].start,newInterval.start),max(intervals[j].end,newInterval.end));
20         }
21         res.push_back(newInterval);
22         for(;j<intervals.size();j++){
23             res.push_back(intervals[j]);
24         }
25         return res;
26     }
27 };

 

Leetcode 57. Insert Interval

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5735405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!