题目:
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:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals =[[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval =[4,8]Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval[4,8]overlaps with[3,5],[6,7],[8,10].
题意:
给定一个Nx2的数组序列,表示一系列的间隔范围,再给定一个间隔范围newInterval,当加上该间隔覆盖后,给出新的数组序列。
解法:
本题思考了整个求解流程,直接将求解流程写出便可解答:
首先,寻找新间隔的起始点在间隔序列中的位置,将新间隔的起始点与间隔序列中的每个间隔终点依次比较,
例如题目例子2,从左向右依次比较,发现新间隔起始点4<间隔[3.5]的终点5,于是可以比较获得覆盖间隔的起始点是MIN[3,4]=3
然后在寻找覆盖间隔的终点,将新间隔的起始点与间隔序列中的每个间隔起点比较,
由上一步的位置,继续从左向右寻找,找到8<12, 所以覆盖点的间隔终点为 MAX[8,10]=10;
然后就可以得到新的间隔序列了。
代码:
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
int i=0;
while(i<intervals.length&&intervals[i][1]<newInterval[0]){
List<Integer> temp=new ArrayList<Integer>();
temp.add(intervals[i][0]);
temp.add(intervals[i][1]);
res.add(temp);
i++;
}
while(i<intervals.length&&intervals[i][0]<=newInterval[1]){
newInterval[0]=Math.min(intervals[i][0],newInterval[0]);
newInterval[1]=Math.max(intervals[i][1],newInterval[1]);
i++;
}
List<Integer> add=new ArrayList<Integer>();
add.add(newInterval[0]);
add.add(newInterval[1]);
res.add(add);
while(i<intervals.length){
List<Integer> temp=new ArrayList<Integer>();
temp.add(intervals[i][0]);
temp.add(intervals[i][1]);
res.add(temp);
i++;
}
int[][] ret=new int[res.size()][2]; //将List转换为返回值类型int[][]
for(int j=0;j<res.size();j++){
ret[j][0]=res.get(j).get(0);
ret[j][1]=res.get(j).get(1);
}
return ret;
}
}
本文深入解析了一种插入区间的算法,旨在解决给定一组按开始时间排序的非重叠区间,如何插入一个新的区间并进行必要合并的问题。通过具体示例说明了算法的执行流程,包括确定新区间起始点的位置、计算覆盖区间的起始和终止点,最终得到更新后的区间序列。
2092

被折叠的 条评论
为什么被折叠?



