Leetcode–Merge Intervals

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:

  1. First needs to sort the list by the start of intervals, use Java collections.sort, but need to implement a comparator.
  2. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s