C# solution, sort then compare with the last item of the result array


  • 0
    B
    public class Solution 
    {
        public IList<Interval> Merge(IList<Interval> intervals) 
        {
            var n = intervals.Count;
            var result = new List<Interval>();
    
            if (intervals.Count == 0) return result;
    
            var orderedIntervals = intervals.OrderBy(c => c.start).ThenBy(c => c.end).ToArray();
    
            result.Add(orderedIntervals[0]);
    
            for (int i = 1; i < orderedIntervals.Length; i++)
            {
                var last = result.Last();
                var cur = orderedIntervals[i];
    
                if (last.end < cur.start)
                {
                    result.Add(cur);
                }
                else
                {
                    last.end = Math.Max(cur.end, last.end);
                }
            }
    
            return result;
        }
    }
    

Log in to reply
 

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