Quantcast
Channel: Leetcode 56: Merge Intervals - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 5

Answer by paparazzo for Leetcode 56: Merge Intervals

$
0
0

Don't use lower case for public and don't us single letters in ctor

 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; } }

Why create a List?

 IEnumerable<Interval> sortedEnumerable = intervals.OrderBy(f => f.start); IList<Interval> sortedIntervals = sortedEnumerable.ToList();

I think this is cleaner

public static IList<Interval> Merge(IList<Interval> intervals){    IList<Interval> nonOverlapped = new List<Interval>();    if (intervals == null || intervals.Count == 0)    {        return nonOverlapped;    }    Interval previous = null;    foreach (Interval current in intervals.OrderBy(f => f.Start))    {                        if(previous == null)        {            previous = current;        }        else if (current.Start > previous.End)        {            /* Two intervals are not overlapped */            nonOverlapped.Add(previous);            previous = current;        }        else        {            /* merge two overlapped intervals */            previous = new Interval(previous.Start, Math.Max(previous.End, current.End));        }    }    nonOverlapped.Add(previous);    return nonOverlapped;}     

Viewing all articles
Browse latest Browse all 5

Trending Articles