标签:
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]
.
Subscribe to see which companies asked this question
问题很简单,直接看代码。
java code:
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class Solution { public List<Interval> merge(List<Interval> intervals) { List<Interval> result = new ArrayList<>(); if(intervals == null || intervals.size() == 0) return result; Collections.sort(intervals, new Comparator<Interval>(){ @Override public int compare(Interval val1, Interval val2) { return Integer.compare(val1.start, val2.start); } }); int start = intervals.get(0).start; int end = intervals.get(0).end; for(Interval val: intervals) { if(val.start <= end) { end = Math.max(end, val.end); }else{ result.add(new Interval(start, end)); start = val.start; end = val.end; } } result.add(new Interval(start, end)); return result; } }
标签:
原文地址:http://blog.csdn.net/itismelzp/article/details/51800491