Skip to content

Instantly share code, notes, and snippets.

@thehoneymad
Created November 21, 2016 21:11
Show Gist options
  • Save thehoneymad/86ba691263d41f0498e4a4bfca719781 to your computer and use it in GitHub Desktop.
Save thehoneymad/86ba691263d41f0498e4a4bfca719781 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace MergeIntervals
{
class Program
{
public static IList<Interval> Merge(IList<Interval> intervals)
{
Queue<Interval> solutionStack = new Queue<Interval>();
intervals = intervals.OrderBy(x => x.start).ToList();
foreach (var item in intervals)
{
if(solutionStack.Count == 0)
{
solutionStack.Enqueue(item);
}
else
{
var peek = solutionStack.Last();
if(peek.end>= item.start)
{
peek.end = item.end > peek.end ? item.end : peek.end;
}
else
{
solutionStack.Enqueue(item);
}
}
}
return solutionStack.ToList();
}
static void Main(string[] args)
{
var collection = new List<Interval>()
{
new Interval() { start = 1, end = 4 },
new Interval() { start = 2, end = 3 }
};
var result = Merge(collection);
foreach (var item in result)
{
System.Console.WriteLine($"[{item.start}, {item.end}]");
}
}
}
public class Interval
{
public int start { get; set; }
public int end { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment