LeetCode/cs/insert-interval.cs

28 lines
794 B
C#
Raw Normal View History

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<int[]>();
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();
}
}