/* * start: 6:38pm * * Need to write efficient interval algorithm * No time out * source code reference: * 1. http://xiaoyaoworm.com/blog/2016/06/27/%E6%96%B0leetcode56-merge-intervals/ * 2. http://juliachencoding.blogspot.ca/2016/07/leetcode-56-merge-intervals.html * * end: 7:07 * walk through the code */ private static long increment(IList <Tuple <int, int> > intervals) { Tuple <int, int>[] sorted = intervals.ToArray(); IComparer <Tuple <int, int> > myComparer = new MyComparer(); Array.Sort(sorted, myComparer); //Array.Reverse(arr); Tuple <int, int> curr = sorted[0]; long sum = 0; for (int i = 1; i < sorted.Length; i++) { Tuple <int, int> runner = sorted[i]; if (curr.Item2 < runner.Item1) { sum += curr.Item2 - curr.Item1 + 1; curr = runner; } int start = curr.Item1; int end = Math.Max(curr.Item2, runner.Item2); curr = new Tuple <int, int>(start, end); } // edge case: sum += curr.Item2 - curr.Item1 + 1; return(sum); }
/* * train tracks on same row * - merge intervals - train track stands for one interval * - sort train tracks by start column * - the array is based on start index 1 not 0 * Add all cells taken by train tracks on the same row. */ private static long SumCellsTakenByTrainTracksForSameRow(IList <Tuple <int, int> > trainTrackOnSameRow) { var trainTracks = trainTrackOnSameRow.ToArray(); IComparer <Tuple <int, int> > myComparer = new MyComparer(); Array.Sort(trainTracks, myComparer); var previous = trainTracks[0]; long cellsTakensByTrainTracks = 0; for (int i = 1; i < trainTracks.Length; i++) { var current = trainTracks[i]; // no overlap if (previous.Item2 < current.Item1) { cellsTakensByTrainTracks += previous.Item2 - previous.Item1 + 1; previous = current; } // reset the previous int start = previous.Item1; int end = Math.Max(previous.Item2, current.Item2); previous = new Tuple <int, int>(start, end); } // edge case: Last one cellsTakensByTrainTracks += previous.Item2 - previous.Item1 + 1; return(cellsTakensByTrainTracks); }