Simple one loop JAVA solution


  • 0
    M
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> ret = new ArrayList<>();
            
            for(Interval i : intervals) {
                // Once new interval is null, then just add the curr interval
                if(newInterval == null) {
                    ret.add(i);
                    continue;
                }
    
                // New interval starts after curr interval end
                if(newInterval.start > i.end) {
                    ret.add(i);
                    continue;
                }
                
                // New interval ends before curr interval start
                if(newInterval.end < i.start) {
                    ret.add(newInterval);
                    ret.add(i);
                    newInterval = null;
                    continue;
                }
                
                // If above both not true, then there is an overlap
                newInterval.start = Math.min(i.start, newInterval.start);
                newInterval.end = Math.max(i.end, newInterval.end);
            }
            
            // Finally add the last new interval
            if(newInterval != null) {
                ret.add(newInterval);
            }
            return ret;
        }
    

Log in to reply
 

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