diff --git a/cs/insert-interval.cs b/cs/insert-interval.cs new file mode 100644 index 0000000..eb21e5b --- /dev/null +++ b/cs/insert-interval.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +public class Solution { + private static int[] Merge(int[] l, int[] r) { + return new int[] { Math.Min(l[0], r[0]), Math.Max(l[1], r[1]) }; + } + + public int[][] Insert(int[][] intervals, int[] newInterval) { + var newIntervals = new List(); + + var i = 0; + for (; i < intervals.Length && intervals[i][1] < newInterval[0]; ++i) { + newIntervals.Add(intervals[i]); + } + + for (; i < intervals.Length && newInterval[1] >= intervals[i][0]; ++i) { + newInterval = Merge(newInterval, intervals[i]); + } + newIntervals.Add(newInterval); + + for (; i < intervals.Length; ++i) { + newIntervals.Add(intervals[i]); + } + + return newIntervals.ToArray(); + } +}