The Problem:
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]
.
Notes:
- First needs to sort the list by the start of intervals, use Java collections.sort, but need to implement a comparator.
- While iterating the list, record the previous one, if found overlap, update the previous one with merged end, then delete the current one.
Java Solution
/** * 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.size()==0) return intervals; Collections.sort(intervals, new Comp()); ListIterator<Interval> iterator = intervals.listIterator(); Interval pre = iterator.next(); while(iterator.hasNext()){ Interval cur = iterator.next(); if(cur.start > pre.end){ pre = cur; continue; } else{ pre.end = Math.max(pre.end, cur.end); iterator.remove(); } } return intervals; } } class Comp implements Comparator<Interval>{ public int compare(Interval a, Interval b){ return a.start-b.start; } }
Advertisements