C# add order and merge solution


  • 0
    Y
    /**
     * Definition for an interval.
     * 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; }
     * }
     */
    public class Solution {
        public IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) {
            //inset
            intervals=intervals.ToList();
            intervals.Add(newInterval);
            //order
            intervals=intervals.OrderBy(aa=>aa.start).ToList();
            int n=intervals.Count;
            if(n < 2)
                return intervals;
            //merge
            var curInt=intervals[0];
            List<Interval> res=new List<Interval>();
            for(int i=1;i<n;i++)
            {
                if(intervals[i].start<=curInt.end)
                {
                    curInt=new Interval(Math.Min(curInt.start,intervals[i].start),Math.Max(curInt.end,intervals[i].end));
                }
                else
                {
                    res.Add(curInt);
                    curInt=intervals[i];
                }
            }
            res.Add(curInt);
            return res;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.