Simple C# solution using Linq


  • 0
    M

    Solution simply sorts list, then runs through the elements checking whether the end of the current interval overlaps the start or end of the next, then merges them if necessary.

    public class Solution {
        public IList<Interval> Merge(IList<Interval> intervals) 
        {
            IList<Interval> retList = new List<Interval>();
            if (intervals.Count == 0)
            {
                return retList;
            }
            var sortedBy1st = intervals.OrderBy(el => el.start);
            Interval currInter = sortedBy1st.First();
            foreach (var inter in sortedBy1st.Skip(1))
            {
                if (currInter.end >= inter.start)
                {
                    currInter.end = Math.Max(currInter.end, inter.end);
                }
                else
                {
                    retList.Add(currInter);
                    currInter = inter;
                }
            }
            
            retList.Add(currInter);
            return retList;
        }
    }
    

Log in to reply
 

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