LeetCode 97 Merge 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].

分析:

先对区间按头排队,用到集合工具类的Collections.sort()方法,因为集合不知道按照头排序,所以我们自己传进去一个比较器当参数。

对排好序的区间检查重复,重复的就合并,直到遇见不重复的区间,将之前重复的合并成一个区间。

/**
 * 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) {
        
        ArrayList<Interval> res = new ArrayList<Interval>();
        if(intervals == null)
            return res;
        //传入一个比较器,制定比较规则
        Collections.sort(intervals, new Comparator<Interval>(){
            public int compare(Interval a, Interval b){
                if(a.start > b.start)
                    return 1;
                else if(a.start == b.start)
                    return 0;
                else
                    return -1;
            }
        });
        
        int i = 0;
        while(i < intervals.size() ){
            int j = i+1;
            int end = intervals.get(i).end;
            while(j<intervals.size() && intervals.get(j).start <= end){
                end = Math.max(end, intervals.get(j).end);
                j++;
            }
            res.add(new Interval(intervals.get(i).start, end));
            i = j;
        }
        
        return res;
        
    }
}


你可能感兴趣的:(LeetCode,merge,Intervals)