Easy to understand java solution


  • 0
    L
     public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        // find the new start and end
        for (int i = 0; i < intervals.size(); i++) {
            Interval element = intervals.get(i);
    
            if (isContains(element, newInterval.start)) {
                newInterval.start = element.start;
            }
    
            if (isContains(element, newInterval.end)) {
                newInterval.end = element.end;
            }
    
            if (element.start > newInterval.end) {
                break;
            }
        }
    
    
        // remove duplicated element
        int insertIndex = 0;
        Iterator<Interval> it = intervals.iterator();
        while (it.hasNext()) {
            Interval element = it.next();
    
            if (isBeContained(element, newInterval)) {
                it.remove();
            } else if (newInterval.start > element.end) {
                insertIndex++;
            } else if (newInterval.end < element.start) {
                break;
            }
        }
    
        intervals.add(insertIndex, newInterval);
    
        return intervals;
    }
    
    private boolean isContains(Interval interval, int i) {
        return i >= interval.start && i <= interval.end;
    }
    
    private boolean isBeContained(Interval interval, Interval newInterval) {
        return newInterval.start <= interval.start && newInterval.end >= interval.end;
    }

Log in to reply
 

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