" Sort the start point,then merge " in Java solution


  • 0
    W
    import java.util.*;
    public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        ArrayList<Interval> result = new ArrayList<Interval>();
        if(intervals.isEmpty()) return result;
        Collections.sort(intervals,new Comparator<Interval>(){//sort the intervals by the start point
            public int compare (Interval it1, Interval it2){
                return it1.start - it2.start;
            }
        });
        result.add(intervals.get(0));
        for(int i=1;i<intervals.size();i++){
            Interval it1 = intervals.get(i);
            Interval it2 = result.get(result.size()-1);
            if(it1.start<=Math.min(it1.end,it2.end)){//Since the start point is sorted, it is enough as long as we review the end point.
                it2.end = Math.max(it1.end,it2.end);
            }else result.add(new Interval(it1.start,it1.end));
        }
        return result;
    }
    

    }


Log in to reply
 

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