verbose java code, beat 95%


  • 0
    C
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> res = new ArrayList<>();
        if(intervals == null || intervals.size() == 0) {
            res.add(newInterval);
            return res;
        }
        int start = 0, end = 0;
        int i = 0;
        for(; i < intervals.size(); i++) {
            if(intervals.get(i).start > newInterval.end) {
                res.add(newInterval);
                res.add(intervals.get(i++));
                break;
            } else if(intervals.get(i).end < newInterval.start) {
                res.add(intervals.get(i));
                if(i == intervals.size() - 1) {
                    res.add(newInterval);
                    return res;
                }
            } else if (intervals.get(i).end >= newInterval.start) {
                start = Math.min(intervals.get(i).start, newInterval.start);
                int j = i+1;
                while(j < intervals.size() && intervals.get(j).start <= newInterval.end)
                    j++;
                end = Math.max(intervals.get(j-1).end, newInterval.end);
                res.add(new Interval(start, end));
                i = j;
                break;
            }
        }
        for(; i < intervals.size(); i++)
            res.add(intervals.get(i));
        
        return res;
    }

Log in to reply
 

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