[Leetcode][JAVA] Insert Interval

时间:2023-03-09 01:17:53
[Leetcode][JAVA] Insert Interval

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为较大的那个值。

注意,如果遍历完了(没有在遍历中插入给定区间), 那么给定区间一定在最后,直接插到数组最后即可。

     public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
int start = newInterval.start;
int end = newInterval.end;
List<Interval> re = new ArrayList<Interval>(intervals);
for(int i=0;i<re.size();i++) {
Interval temp = re.get(i);
if(end<temp.start) {
re.add(i, new Interval(start, end));
return re;
}
if(temp.end<start)
continue;
else {
start = Math.min(temp.start, start);
end = Math.max(temp.end, end);
re.remove(i);
i--;
}
}
re.add(new Interval(start, end));
return re;
}