forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0056-merge-intervals.cs
32 lines (27 loc) · 956 Bytes
/
0056-merge-intervals.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution
{
public int[][] Merge(int[][] intervals)
{
var sortedInterval = intervals.Clone() as int[][];
Array.Sort(sortedInterval, (a, b) => a[0] - b[0]);
var mergedInterval = new List<int[]>();
var lastInterval = sortedInterval[0];
mergedInterval.Add(lastInterval);
for (var i = 1; i < sortedInterval.Length; i++)
{
var current = sortedInterval[i];
var lastIntervalEnd = lastInterval[1];
var nextIntervalEnd = current[1];
var nextIntervalStart = current[0];
if (lastIntervalEnd >= nextIntervalStart)
lastInterval[1] = Math.Max(nextIntervalEnd, lastIntervalEnd);
else
{
lastInterval = current;
mergedInterval.Add(lastInterval);
//lastInterval = current;
}
}
return mergedInterval.ToArray();
}
}