Damn simple java impl, sort , comparator


  • 1
    Z
     /**
      * Sort : smaller start, smaller end time
      * Decide merge or not.
      */ 
    public class Solution {
        public List<Interval> merge(List<Interval> ins) {
            List<Interval> ret = new ArrayList<>();
            ins.sort(new Comp());
    
            Interval prev = null;
            for(Interval in: ins){
                if(prev == null){ // init
                    prev = in;
                    ret.add(prev);
                    continue;
                }
    
                if(prev.end >= in.start){ // should merge
                    prev.end = Math.max(prev.end, in.end);
                }
                else{
                    prev = in;
                    ret.add(prev);
                }
            }
    
            return ret; 
        }
    
        class Comp implements Comparator<Interval>{
            public int compare(Interval o1, Interval o2){
                int diff = o1.start - o2.start;
                return diff != 0? diff: o1.end - o2.end;
            }
        }
    }

Log in to reply
 

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