首页 > 代码库 > Merge Intervals
Merge Intervals
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]
.
答案
/** * 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) { if (intervals == null || intervals.size() <= 1) { return intervals; } Collections.sort(intervals, new Comparator<Interval>() { public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } }); int i = 0; while (i < intervals.size() - 1) { if (intervals.get(i).end >= intervals.get(i + 1).start) { intervals.get(i).start = Math.min(intervals.get(i).start, intervals.get(i + 1).start); intervals.get(i).end = Math.max(intervals.get(i).end, intervals.get(i + 1).end); intervals.remove(i + 1); i-- ; } else { i++ ; } if (i < 0) { i++ ; } } return intervals; } }
Merge Intervals
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。