cs: add «57. Insert Interval»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-03-18 00:12:11 +01:00
parent c228a24b1a
commit e9815ea0aa
Signed by: mfocko
GPG key ID: 7C47D46246790496

27
cs/insert-interval.cs Normal file
View file

@ -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<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();
}
}