350ms Java Solution


  • 0
    K
    public class Solution {
        class IntervalComparator implements Comparator<Interval> {
            @Override
            public int compare(Interval a, Interval b) {
                return a.start > b.start ? 1 : ((a.start == b.start) ? 0 : -1);
            }
        }
        
        public List<Interval> merge(List<Interval> intervals) {
            if(intervals == null || intervals.isEmpty()) return intervals;
            
            // sort by start  
            Collections.sort(intervals, new IntervalComparator());
            
            List<Interval> result = new ArrayList<Interval> ();
            Interval merge = new Interval(intervals.get(0).start, intervals.get(0).end);
            
            for(int i=1; i<intervals.size(); i++) {
                Interval curr = intervals.get(i);
                if(merge.end < curr.start) {
                    result.add(merge);
                    merge = curr;
                } else {
                    merge = new Interval(
                        Math.min(merge.start, curr.start),
                        Math.max(merge.end, curr.end)
                    );
                }
            }
            result.add(merge);
            
            return result;
        }
    }

Log in to reply
 

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