Merge Intervals, Leetcode 解题笔记

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

这道题思路不难,很容易想到先将intervals排序,然后再合并。这题关键考察的是Comparator的override的知识点。与此题类似的可以复习之前做过的Merge k sorted lists那道题。

/**
 * 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> merge(ArrayList<Interval> intervals) {
        if(intervals == null || intervals.size() <= 1) return intervals;
        
        //注意学习此处sort list的用法
        Collections.sort(intervals, new IntervalComparator());
        ArrayList<Interval> ret = new ArrayList<Interval>();

        Interval pre = intervals.get(0);
        for(int i = 1; i < intervals.size(); i++){
            Interval cur = intervals.get(i);
            if(cur.start <= pre.end){
                Interval temp = new Interval(pre.start, Math.max(cur.end, pre.end));
                pre = temp;
            }
            else{
                ret.add(pre);
                pre = cur;
            }
        }
        ret.add(pre);
        return ret;
    }
}

//构建自定义的Comparator
class IntervalComparator implements Comparator<Interval>{
    public int compare(Interval i1, Interval i2){
        return i1.start - i2.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