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].
The key to solving this problem is defining a Comparator first to sort the ArrayList of Intervals. And then merge some intervals. The take-away message from this problem is utilizing the advantage of sorted list/array
class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public class Solution { public ArrayList<Interval> merge(ArrayList<Interval> intervals) { if (intervals == null || intervals.size() <= 1) return intervals; // sort intervals by using self-defined Comparator Collections.sort(intervals, new IntervalComparator()); ArrayList<Interval> result = new ArrayList<Interval>(); Interval prev = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { Interval curr = intervals.get(i); if (prev.end >= curr.start) { // merged case Interval merged = new Interval(prev.start, Math.max(prev.end, curr.end)); prev = merged; } else { result.add(prev); prev = curr; } } result.add(prev); return result; } } class IntervalComparator implements Comparator<Interval> { public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }
Insert Interval in Java
Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
/** * 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 ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> result = new ArrayList<Interval>(); for(Interval interval: intervals){ if(interval.end < newInterval.start){ result.add(interval); }else if(interval.start > newInterval.end){ result.add(newInterval); newInterval = interval; }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){ newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end)); } } result.add(newInterval); return result; } }