Java AC Solution


  • 0
    G
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> res = new ArrayList<>();
            int insertAt=intervals.size();
            
            for(int i=0;i<intervals.size();i++) {
                Interval curr = intervals.get(i);
                if(overlap(curr, newInterval)) {
                    newInterval=getOverlap(curr, newInterval);
                    intervals.remove(i);
                    insertAt = i;
                    i--;
                } else if(newInterval.end < curr.start) {
                    insertAt = i;
                    break;
                }
            }
            intervals.add(insertAt, newInterval);
            return intervals;
            
        }
        
        public Interval getOverlap(Interval i, Interval j) {
            return new Interval(Math.min(i.start, j.start), Math.max(i.end, j.end));
        }
        
        public boolean overlap(Interval i, Interval j) {
            return (j.start<=i.end && j.start>=i.start )|| (i.start<=j.end && i.start>=j.start );
        }
    

Log in to reply
 

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