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

 

/**
 * 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) {
    	List<Interval> res = new ArrayList<Interval>();
    	Collections.sort(intervals, new Comparator<Interval>() {
			@Override
			public int compare(Interval o1, Interval o2) {
				if (o1.start > o2.start) {
					return 1;
				} else if (o1.start < o2.start) {
					return -1;
				} else {
					return 0;
				}
			}
		});
    	Interval toCompare = null;
    	for (Interval in : intervals) {
    		if (toCompare!=null && in.start<=toCompare.end && in.end>=toCompare.start) {
    			toCompare.start = Math.min(in.start, toCompare.start);
    			toCompare.end = Math.max(in.end, toCompare.end);
    		} else {
    			if (toCompare!=null) {
    				res.add(toCompare);
    			}
    			toCompare = in;
    		}
    	}
    	if (toCompare!=null) {
			res.add(toCompare);
		}
    	return res;
    }
}

 

你可能感兴趣的:(merge)