[JAVA] Share my java solution


  • 1
    L
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if(intervals==null || intervals.size()==0) return new LinkedList<Interval>();
            
            
            Collections.sort(intervals, new Comparator<Interval>() {
                public int compare(Interval o1, Interval o2) {
                    return o1.start - o2.start;
                }
            });
    
            List<Interval> result = new LinkedList<Interval>();
            Interval iv = null, ik = null;
            Iterator<Interval> it = intervals.iterator();
            while(it.hasNext()){
                iv = it.next();
                if(ik==null) ik = new Interval(iv.start, iv.end);
                else{
                    if(iv.start<=ik.end){
                        ik = new Interval(ik.start, Math.max(iv.end, ik.end));
                    }
                    else{
                        result.add(ik);
                        ik = iv;
                    }
                }
            }
            if(ik!=null) result.add(ik);
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.