Clean Java O(N) Code


  • 0
    /**
     * 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; }
     * }
     */
    class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> res = new ArrayList<>();
            int idx = 0;
            for (; idx < intervals.size(); idx++) {
                if (intervals.get(idx).start > newInterval.start) {
                    break;
                }
            }
            intervals.add(idx, newInterval);
            Interval pre = intervals.get(0);
            for (int i = 1; i < intervals.size(); i++) {
                Interval curr = intervals.get(i);
                if (curr.start <= pre.end) {
                    pre.end = Math.max(pre.end, curr.end);
                } else {
                    res.add(pre);
                    pre = curr;
                }
            }
            res.add(pre);
            return res;
        }
    }
    

Log in to reply
 

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