My Java solution, 12ms


  • 0
    A
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if(intervals == null || intervals.size() <= 1) return intervals;
            
            Collections.sort(intervals, new Comparator<Interval>() {
               public int compare(Interval a, Interval b) {
                   return Integer.compare(a.start, b.start);
               }
            });
            
            List<Interval> res = new ArrayList<>();
            Interval curr = intervals.get(0);
            for(int i = 1; i < intervals.size(); i++) {
                if(intervals.get(i).start <= curr.end) { // merged
                    curr.end = Math.max(curr.end, intervals.get(i).end);
                } else {
                    res.add(curr);
                    curr = intervals.get(i);
                }
            }
            res.add(curr);
            return res;
        }
    }
    

Log in to reply
 

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