Created
June 29, 2017 22:22
-
-
Save jianminchen/8c7e20a3e41f194e34b0111dc3034390 to your computer and use it in GitHub Desktop.
Leetcode 57 - insert intervals - code review on June 29, 2017
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace _57InsertIntervals | |
{ | |
/// <summary> | |
/// Leetcode 57 | |
/// https://leetcode.com/problems/insert-interval/?tab=Description#/description | |
/// code review on June 29, 2017 | |
/// source code reference: | |
/// http://simpleandstupid.com/2014/10/29/insert-interval-leetcode-%E8%A7%A3%E9%A2%98%E7%AC%94%E8%AE%B0/ | |
/// </summary> | |
public class Interval | |
{ | |
public int start; | |
public int end; | |
public Interval() | |
{ | |
start = 0; | |
end = 0; | |
} | |
public Interval(int s, int e) | |
{ | |
start = s; | |
end = e; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
/* | |
* 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]. | |
*/ | |
// public IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) { | |
public static IList<Interval> insert(IList<Interval> intervals, Interval newInterval) | |
{ | |
var result = new List<Interval>(); | |
foreach (var interval in intervals) | |
{ | |
if (interval.end < newInterval.start) | |
{ | |
result.Add(interval); | |
} | |
else if (interval.start > newInterval.end) | |
{ | |
result.Add(newInterval); | |
newInterval = interval; | |
} | |
else if (interval.end >= newInterval.start || | |
interval.start <= newInterval.end) | |
{ | |
newInterval = new Interval( | |
Math.Min(interval.start, newInterval.start), | |
Math.Max(newInterval.end, interval.end)); | |
} | |
} | |
result.Add(newInterval); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment