Two ends search JAVA


  • 0
    W
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> left = new LinkedList<>();
            List<Interval> right = new LinkedList<>();
            for (int i = 0; i < intervals.size(); i++) {
                Interval in = intervals.get(i);
                if (in.end < newInterval.start) {
                    left.add(in);
                } else {
                    newInterval.start = Math.min(newInterval.start, in.start);
                    break;
                }
            }
            for (int i = intervals.size() - 1; i >= 0; i--) {
                Interval in = intervals.get(i);
                if (in.start > newInterval.end) {
                    right.add(0, in);
                } else {
                    newInterval.end = Math.max(newInterval.end, in.end);
                    break;
                }
            }
            left.add(newInterval);
            left.addAll(right);
            return left;
        }
    

Log in to reply
 

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