Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals
Given intervals
[1,3],[6,9]
, insert and merge [2,5]
in as [1,5],[6,9]
.
Example 2:
Given
Given
[1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge [4,9]
in as [1,2],[3,10],[12,16]
.
This is because the new interval
[4,9]
overlaps with [3,5],[6,7],[8,10]
.Idea: Easy question. Linear visiting.
/** * 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 ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { // Start typing your Java solution below // DO NOT write main() function boolean merge = false; for (int i=0; i<intervals.size(); i++) { Interval inv = intervals.get(i); if (newInterval.start <= inv.start && newInterval.end >= inv.start) { merge = true; inv.start = newInterval.start; } else if (newInterval.start <= inv.end && newInterval.start >= inv.start) { merge = true; } if (merge) { //find end for (int j = i; j<intervals.size(); j++) { inv = intervals.get(j); if (inv.end >= newInterval.end) { break; } else if (j+1 < intervals.size() && newInterval.end <= intervals.get(j+1).start) { inv.end = newInterval.end; break; } else if (j+1 >= intervals.size()) { inv.end = newInterval.end; break; } else { if (j+1 < intervals.size()) { inv.end = intervals.get(j+1).start; } } } break; } else { if (newInterval.start > inv.end && i+1 < intervals.size() & & intervals.get(i+1).start > newInterval.end) { intervals.add(i+1, newInterval); return intervals; } else if (newInterval.start > inv.end && i+1 == intervals.size()) { intervals.add(newInterval); return intervals; } else if (newInterval.end < inv.start) { intervals.add(i, newInterval); return intervals; } } } ArrayList<Interval> result = new ArrayList<Interval>(); if (merge) { for (int i=0; i<intervals.size(); i++) { Interval inv = intervals.get(i); result.add(inv); for (int j=i+1; j<intervals.size(); j++) { if (inv.end == intervals.get(j).start) { inv.end = intervals.get(j).end; i = j; } } } } else { if (intervals.size() == 0) { intervals.add(newInterval); } return intervals; } return result; } }
No comments:
Post a Comment