标签:
public IList<Interval> Merge(IList<Interval> intervals) { if(intervals == null || intervals.Count == 0){ return new List<Interval>(); } var result = new List<Interval>(); intervals = intervals.OrderBy(s=>s.start).ToList(); var len = intervals.Count; for(var i = 0;i < len; i++){ // - add or merge into result bool merged = false; foreach(var r in result){ // |-------| : r // |---| : intervals[i] if(r.end < intervals[i].start){ // no interset continue; } // |-------| : r // |---| : intervals[i] else if(r.end == intervals[i].start){ r.end = intervals[i].end; merged = true; break; } // |------------------| : r // |-----| : intervals[i] else if(r.end >= intervals[i].end){ // do nothing merged = true; break; } // |--------| : r // |--------| : intervals[i] else if(r.end < intervals[i].end){ r.end = intervals[i].end; merged = true; break; } } if(!merged){ result.Add(intervals[i]); } } return result; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/47257907