merge Interval

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
# 1 based on start  26ms
/**
 * 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 merge(List intervals) {
        List res = new ArrayList();
        if(intervals == null || intervals.size() <= 1) return intervals;
        Collections.sort(intervals, new Comparator(){
            public int compare(Interval a, Interval b){
                return a.start - b.start;
            }
        });
        
        int start = intervals.get(0).start;
        int end = intervals.get(0).end;
        
        for(Interval interval : intervals){
            if(interval.start <= end){
                end = Math.max(end, interval.end);
            } else {
                res.add(new Interval(start, end));
                start = interval.start;
                end = interval.end;
            }
        }
        res.add(new Interval(start, end));
   
        return res;
    }
}
# 2 based on end  24ms
public class Solution {
    public List merge(List intervals) {
        List res = new ArrayList();
        if(intervals == null || intervals.size() <= 1) return intervals;
        Collections.sort(intervals, new Comparator(){
            public int compare(Interval a, Interval b){
                return b.end - a.end;
            }
        });
        
        Interval last = intervals.get(0);
        Interval cur = null;
        for(int i = 1; i < intervals.size(); i++){
            cur = intervals.get(i);
            if(last.start > cur.end){
                res.add(last);
                last = cur;
            } else {
                last.start = Math.min(cur.start, last.start);
            }
        }
        res.add(last);
        
        Collections.reverse(res);
        
        return res;
    }
}
# number of meeting rooms, 拆分start,end  20ms
public class Solution {
    public List merge(List intervals) {
        int n = intervals.size();
        int[] starts = new int[n];
        int[] ends = new int[n];
        for(int i=0; i res = new ArrayList();
        for(int i=0, j=0; i ends[i]){  // next meeting starts after this ends, cant merge
                res.add(new Interval(starts[j], ends[i]));
                j = i + 1;
            }
        }
        return res;
    }
}

你可能感兴趣的:(java,interval)