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

Answer by Zuabros for Leetcode 56: Merge Intervals

$
0
0

Using a list allows just excluding redundant intervals. I think it is cleaner. The trick is backwarding the counter when you remove an element. Some people say against using "Math.Max", but the execution time difference is negligible and makes the code much easier to read.

public int[][] Merge(int[][] inter) {var list = inter.OrderBy(x=>x[0]).ToList(); // SORT INTERVALS BY STARTfor (int i=1;i<list.Count;i++)    if (list[i][0]<=list[i-1][1]) // interval2 starts before or at interval1 end    {        list[i-1][1]=Math.Max(list[i][1],list[i-1][1]); // merge        list.RemoveAt(i--); // delete redundant interval and backwards counter    }return list.ToArray();}

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>