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 [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
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].
乍看起来不难的一题,但实现的时候还是需要很清晰的逻辑才能用简洁代码完成。
把遍历时的情况列举一下,无非就三种:
1. 当前区间的end小于给定区间的start, 则continue;
2. 当前区间的start大于给定区间的end, 说明给定区间正好在它前面,直接把给定区间插入在当前区间前并停止遍历。
3. 当前区间与给定区间有重叠。
主要是第三种情况比较复杂,细分的话还能分成好几种情况。实际上不需要考虑这么细致,如果只关心最后插入的区间,那么就不用过多考虑中间遍历到的有重叠的区间,只需要根据它们的start和end来调整最后插入的给定区间范围,然后删去它们即可。
具体的调整方法为: 给定区间的start为当前区间start与给定区间start的小的那个值。end为较大的那个值。
注意,如果遍历完了(没有在遍历中插入给定区间), 那么给定区间一定在最后,直接插到数组最后即可。
1 public List<Interval> insert(List<Interval> intervals, Interval newInterval) { 2 int start = newInterval.start; 3 int end = newInterval.end; 4 List<Interval> re = new ArrayList<Interval>(intervals); 5 for(int i=0;i<re.size();i++) { 6 Interval temp = re.get(i); 7 if(end<temp.start) { 8 re.add(i, new Interval(start, end)); 9 return re; 10 } 11 if(temp.end<start) 12 continue; 13 else { 14 start = Math.min(temp.start, start); 15 end = Math.max(temp.end, end); 16 re.remove(i); 17 i--; 18 } 19 } 20 re.add(new Interval(start, end)); 21 return re; 22 }
浙公网安备 33010602011771号