Wednesday, March 6, 2013

Merging 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].

Solution:

We first sort the list according to the start value. Then for any interval i in the middle, it has overlap with the next interval j if j.start <= i.end. If so, we know we are about to merge them into a new interval k. And k.start = i.start && k.end = max(i.end, j.end).

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class MergeIntervals {

public class Interval
{
public int start;
public int end;

public Interval(int start, int end) {
super();
this.start = start;
this.end = end;
}
}

public class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
Interval i1 = (Interval) o1;
Interval i2 = (Interval) o2;
return i1.start - i2.start;
}
}

public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if (intervals == null)
return null;
ArrayList<Interval> result = new ArrayList<Interval>();
if (intervals.size() == 0)
return result;
if (intervals.size() == 1) {
result.addAll(intervals);
return result;
}
Collections.sort(intervals, new MyComparator());
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for (int i = 1; i < intervals.size(); ++i) {
Interval curr = intervals.get(i);
if (curr.start <= end) {
end = Math.max(end, curr.end);
} else {
result.add(new Interval(start, end));
start = curr.start;
end = curr.end;
}
}
result.add(new Interval(start, end));
return result;
}
}

No comments: