56. Merge Intervals
程序员文章站
2022-06-04 17:52:06
...
原题
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
代码实现
first, sort by start for every interval asc.
Then, discuss every interval’s end point.
public IList<Interval> Merge(IList<Interval> intervals)
{
if(intervals.Count==0|| intervals.Count==1) return intervals;
var rtn = new List<Interval>();
var s = intervals.OrderBy(r => r.start).ToList();
rtn.Add(s[0]);
for (int i = 1; i < s.Count; i++)
{
//analysis and discuss every interval's end point
//overlap wholely
if (rtn[rtn.Count - 1].end >= s[i].end)
{
continue;
}
//overlap partly
else if (rtn[rtn.Count - 1].end >= s[i].start)
{
rtn[rtn.Count-1].end = s[i].end;
}
else //no overlap
{
rtn.Add(s[i]);
}
}
return rtn;
}
题库
Leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp
推荐阅读
-
PHP合并数组+与array_merge的区别分析_php技巧
-
php通过array_merge()函数合并两个数组的方法,array_merge数组_PHP教程
-
array_merge的10篇内容推荐
-
php array_merge下进行数组合并的代码
-
MySQL中实现插入或更新操作(类似Oracle的merge语句)
-
MySQL中实现插入或更新操作(类似Oracle的merge语句)
-
SQL Server使用Merge语句当源表数据集为空时,无法进行查询的问题
-
PHP使用array_merge重新排列数组下标的方法
-
php数组合并array_merge()函数使用注意事项
-
JDK 1.8 之 Map.merge()