public IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) { IList<Interval> result = new List<Interval>(); int i = 0; Interval current = null; for (; i < intervals.Count; i++) { current = intervals[i]; if (newInterval.start <= current.end) break; result.Add(current); current = intervals[i]; } if (i == intervals.Count) { result.Add(newInterval); return result; } if(newInterval.end <= current.start) { current = newInterval; } else { current.start = Math.Min(current.start, newInterval.start); current.end = Math.Max(current.end, newInterval.end); i++; } for (; i < intervals.Count; i++) { Interval next = intervals[i]; if (next.start > current.end) { result.Add(current); current = next; } else { current.end = Math.Max(current.end, next.end); } } result.Add(current); return result; }
private int comparerInterval(Interval a, Interval b) { if (a.start > b.start) return 1; else if (a.start < b.start) return -1; else return 0; }