leetcode 28: Merge Intervals

来源:互联网 发布:me域名多少钱 编辑:程序博客网 时间:2024/06/07 12:00
import java.util.*;
public class Solution {  
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {  
        // Start typing your Java solution below  
        // DO NOT write main() function  
        ArrayList<Interval> res = new ArrayList<Interval>();  
          
        int sz = intervals.size();  
        if(sz<1) return res;  
          
        Collections.sort(intervals, new IntervalComparator());  
        res.add(new Interval(intervals.get(0).start, intervals.get(0).end ) ); //this won't modify the original input.  
          
        for(int i=1; i<sz; i++) {  
            Interval last = res.get(res.size()-1);  
            Interval x = intervals.get(i);  
              
            if(last.end < x.start) {  
                res.add( new Interval(intervals.get(i).start, intervals.get(i).end ) );  
            } else if( last.end < x.end) {  
                last.end = x.end;  
            }  
        }  
        return res;  
    }  
      
    class IntervalComparator implements Comparator<Interval>{  
        public int compare(Interval a, Interval b) {  
            if(a.start < b.start) return -1;  
            else if(a.start>b.start) return 1;  
            else {  
                if(a.end<b.end) return -1;  
                else if(a.end>b.end) return 1;  
                else return 0;  
            }  
        }  
    }  
0 0
原创粉丝点击