Sort and Merge Java Solution. Beats 70%


  • 0
    K
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            List<Interval> ls = new LinkedList<>();
            if(intervals.size() < 1) return ls;
            //Sort the intervals
            intervals.sort((obj1, obj2) -> { return obj1.start-obj2.start; });
            Interval first = intervals.get(0);
            for(int i=1; i<intervals.size(); i++) {
            	Interval in = intervals.get(i);
                    // if the min of current interval falls within the range of previous interval, merge the intervals. 
                    //otherwise, add the interval to the final list.
            	if(in.start >= first.start && in.start <= first.end) {
            		first.end = (first.end>in.end)?first.end:in.end;
            	} else {
            		ls.add(first);
            		first = in;
            	}
            }
            ls.add(first);
            return ls;
        }
    }
    

Log in to reply
 

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