Leetcode 57: Insert Interval

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 57: Insert Interval相关的知识,希望对你有一定的参考价值。

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].

 

 

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     public int start;
 5  *     public int end;
 6  *     public Interval() { start = 0; end = 0; }
 7  *     public Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 public class Solution {
11     public IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) {
12         var result = new List<Interval>();
13         
14         int i = 0;
15         
16         while (i < intervals.Count)
17         {
18             if (newInterval.start <= intervals[i].start)
19             {
20                 Append(result, newInterval);
21                 newInterval = intervals[i];
22             }
23             else
24             {
25                 Append(result, intervals[i]);
26             }
27             
28             i++;
29         }
30         
31         Append(result, newInterval);
32         
33         return result;
34     }
35     
36     private void Append(IList<Interval> intervals, Interval newInterval)
37     {
38         if (intervals.Count == 0 || newInterval.start > intervals[intervals.Count - 1].end)
39         {
40             intervals.Add(newInterval);
41         }
42         else 
43         {
44             intervals[intervals.Count - 1].end = Math.Max(intervals[intervals.Count - 1].end, newInterval.end);
45         }
46     }
47 }

 



以上是关于Leetcode 57: Insert Interval的主要内容,如果未能解决你的问题,请参考以下文章

一天一道LeetCode#57. Insert Interval

Leetcode57 Insert Interval

LeetCode57 Insert Interval

Leetcode 57: Insert Interval

leetcode 57. Insert Interval

[LeetCode] 57. Insert Interval Java