JAVA AC answer. beat 87%


  • 0
    H

    Sort the list which takes nlogn time and do a O(n) iteration.

    public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        if (intervals.size()==0) return intervals;
        Collections.sort(intervals, new Comparator<Interval>(){
            @Override
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        List<Interval> result = new ArrayList<>();
        for (int i = 0; i<intervals.size(); i++) {
            if (i>0) {
                if (intervals.get(i).start>intervals.get(i-1).end) {
                    result.add(intervals.get(i-1));
                }
                else {
                    intervals.set(i, new Interval(intervals.get(i-1).start, Math.max(intervals.get(i).end, intervals.get(i-1).end)));
                }
            }
            if (i==intervals.size()-1) result.add(intervals.get(i));
        }
        
        return result;
    }
    }

Log in to reply
 

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