Simple Solution in C#


  • 0
    P
            public IList<Interval> Merge(IList<Interval> intervals)
            {
                if (intervals == null || intervals.Count <= 1) return intervals;
    
                intervals = intervals.OrderBy(a => a.start).ToList();
                
                List<Interval> output = new List<Interval>();
                Interval match = intervals[0];
    
                for (int i = 1; i < intervals.Count; i++)
                {
                    if (match.end < intervals[i].start)
                    {
                        output.Add(match);
                        match = intervals[i];
                    }
                    else if (match.end >= intervals[i].start && match.end < intervals[i].end)
                    {
                        match.end = intervals[i].end;
                    }
                }
                output.Add(match);
    
                return output;
            }
    

Log in to reply
 

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