Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 23, 2017 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/2d62b4c5f70e553310d423a861428c4b to your computer and use it in GitHub Desktop.
Save jianminchen/2d62b4c5f70e553310d423a861428c4b to your computer and use it in GitHub Desktop.
Leetcode 56 - Merge Intervals - pass leetcode online judge
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MergeIntervals
{
class Program
{
/**
* Definition for an interval.
*/
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; }
}
static void Main(string[] args)
{
RunSampleTestcase1();
RunSampleTestcase2();
}
/*
* Test case:
* help to test intervals should be sorted first before merging.
* [1,4], [0,4] should not be [1,4]
*/
public static void RunSampleTestcase1()
{
IList<Interval> intervals = new List<Interval>();
intervals.Add(new Interval(1, 4));
intervals.Add(new Interval(0, 4));
IList<Interval> nonoverlapped = Merge(intervals);
Debug.Assert(nonoverlapped[0].start == 0 && nonoverlapped[0].end == 4);
}
/*
* Test case:
* help to test that edge case is handled properly .
* [1,4] should be [1,4], not []
* In other words, there is one interval in the input, the result should be itself.
* For loop
*/
public static void RunSampleTestcase2()
{
IList<Interval> intervals = new List<Interval>();
intervals.Add(new Interval(1, 4));
IList<Interval> nonoverlapped = Merge(intervals);
Debug.Assert(nonoverlapped.Count == 1);
}
/*
* Merge all overlapping intervals
* Output: all intervals are non-overlapped.
*
* Use LINQ to sort the intervals -
* http://stackoverflow.com/questions/15486/sorting-an-ilist-in-c-sharp
*/
public static IList<Interval> Merge(IList<Interval> intervals)
{
IList<Interval> nonOverlapped = new List<Interval>();
if(intervals == null || intervals.Count == 0)
{
return nonOverlapped;
}
IEnumerable<Interval> sortedEnumerable = intervals.OrderBy(f => f.start);
IList<Interval> sortedIntervals = sortedEnumerable.ToList();
Interval previous = sortedIntervals[0];
for (int i = 1; i < sortedIntervals.Count; i++)
{
Interval current = sortedIntervals[i];
if(previous.end < current.start)
{
nonOverlapped.Add(previous);
previous = current;
continue;
}
previous = new Interval(previous.start, Math.Max(previous.end, current.end));
}
// edge case
nonOverlapped.Add(previous);
return nonOverlapped;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment