首页 > 代码库 > LeetCode Merge Intervals
LeetCode 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]
.
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */10 class intervalComparator implements Comparator<Interval>{11 @Override12 public int compare(Interval o1, Interval o2) {13 return o1.start-o2.start;14 }15 }16 public class Solution {17 public List<Interval> merge(List<Interval> intervals) {18 List<Interval> result = new ArrayList<Interval>();19 if (intervals.size() == 0) {20 return result;21 }22 Collections.sort(intervals, new intervalComparator());23 Interval first = intervals.get(0);24 Interval next;25 for (int i = 1; i <intervals.size() ; i++) {26 next = intervals.get(i);27 if (first.end < next.start) {28 result.add(first);29 first = next;30 } else {31 if (first.end < next.end) {32 first.end = next.end;33 } 34 }35 }36 result.add(first);37 return result;38 }39 }
LeetCode Merge Intervals
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。