Java code using listIterator


  • 0
    R
    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    public class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            if(newInterval==null){
                return intervals;
            }
            if(intervals==null){
                intervals = new LinkedList<Interval>();
            }
            Interval previous = newInterval;
            ListIterator<Interval> listIterator = intervals.listIterator();
            while(listIterator.hasNext()) {
                Interval current = listIterator.next();
                if(previous.end < current.start){
                    listIterator.previous();
                    listIterator.add(previous);
                    return intervals;
                } else if(previous.start>current.end){
                } else{
                    listIterator.remove();
                    previous = new Interval(Math.min(previous.start, current.start), Math.max(previous.end, current.end));
                }
            }
            intervals.add(previous);
            return intervals;
            
        }
    }
    

Log in to reply
 

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