My C# solution with SortedSet


  • 0
    S
    public class Solution {
        public IList<Interval> Merge(IList<Interval> intervals) 
        {
            var result = new List<Interval>();
            if(intervals == null || intervals.Count == 0)
                return result;
            var sortedSet = new SortedSet<Interval>(Comparer<Interval>.Create((a,b) => a.start==b.start?a.end-b.end:a.start-b.start));
            foreach(var node in intervals)
            {
                sortedSet.Add(node);
            }
            
            while(sortedSet.Count() > 0)
            {
                if(sortedSet.Count() == 1)
                {
                    result.Add(sortedSet.Min);
                    break;
                }
                else
                {
                    var node1 = sortedSet.Min;
                    sortedSet.Remove(sortedSet.Min);
                    var node2 = sortedSet.Min;
                    sortedSet.Remove(sortedSet.Min);
                    if(node1.end >= node2.start)
                    {
                        sortedSet.Add(new Interval(node1.start, Math.Max(node1.end, node2.end)));
                    }
                    else
                    {
                        result.Add(node1);
                        sortedSet.Add(node2);
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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