Java solution beat 86%


  • 0
    H
    public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        // 86%
        if(intervals.size() <= 1) return intervals;
        
        List<Interval> res = new ArrayList<>();
        Interval[] intvls = new Interval[intervals.size()];
        intervals.toArray(intvls);
        Arrays.sort(intvls, new IntervalComparator());
        
        int s = intvls[0].start;
        int e = intvls[0].end;
        
        for(Interval interval : intvls) {
            if(e < interval.start) {
                res.add(new Interval(s, e));
                s = interval.start;
                e = interval.end;
            } else {
                e = e > interval.end ? e : interval.end;
            }
        }
        res.add(new Interval(s, e));
        return res;
    }
    
    public class IntervalComparator implements Comparator<Interval> {
        public int compare(Interval i1, Interval i2) {
            return i1.start - i2.start;
        }
    }
    

    }


Log in to reply
 

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