Very simple solution in Java (insert new interval in the list and perform a merge)


  • 0
    D
    class Solution
    {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval)
        {
        	intervals.add(newInterval);
        	Collections.sort(intervals, new SortByStart());
        	int i=1;
            while(i<intervals.size())
            {
            	if(intervals.get(i-1).end >= intervals.get(i).start)
            	{
            		intervals.get(i-1).end = Math.max(intervals.get(i-1).end, intervals.get(i).end);
            		intervals.remove(i);
            	}
            	else
            	{
            		i++;
            	}
            }
            return intervals;
        }
    }
    class SortByStart implements Comparator<Interval>
    {
    	public int compare(Interval a, Interval b)
    	{
    		return a.start-b.start;
    	}
    }
    
    

Log in to reply
 

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