LeetCode 57. 插入区间
题目描述
✅ 57. 插入区间
思路分析
解法一:扫描合并区间(推荐)
核心思路:
- 先加入所有在
newInterval左侧且不相交的区间。- 与后续有交集的区间合并成一个新区间。
- 最后加入剩余区间。
复杂度分析:
- 时间复杂度:O(n),其中 n 表示区间数量。
- 空间复杂度:O(1),除结果外仅使用常数额外空间。
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
int n = intervals.length;
int i = 0;
List<int[]> res = new ArrayList<>();
// 加入完全在左侧的区间
while (i < n && intervals[i][1] < newInterval[0]) {
res.add(intervals[i]);
i++;
}
int start = newInterval[0];
int end = newInterval[1];
// 合并所有有重叠的区间
while (i < n && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
res.add(new int[]{start, end});
// 加入剩余区间
while (i < n) {
res.add(intervals[i]);
i++;
}
return res.toArray(new int[res.size()][]);
}
}
func insert(intervals [][]int, newInterval []int) [][]int {
n := len(intervals)
res := make([][]int, 0, n+1)
i := 0
// 加入完全在左侧的区间
for i < n && intervals[i][1] < newInterval[0] {
res = append(res, intervals[i])
i++
}
start, end := newInterval[0], newInterval[1]
// 合并所有有重叠的区间
for i < n && intervals[i][0] <= end {
if intervals[i][0] < start {
start = intervals[i][0]
}
if intervals[i][1] > end {
end = intervals[i][1]
}
i++
}
res = append(res, []int{start, end})
// 加入剩余区间
for i < n {
res = append(res, intervals[i])
i++
}
return res
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 56. 合并区间 | 中等 | 区间合并 |
| 986. 区间列表的交集 | 中等 | 双指针 |
| 435. 无重叠区间 | 中等 | 贪心 |
| 452. 用最少数量的箭引爆气球 | 中等 | 区间贪心 |
| 1288. 删除被覆盖区间 | 中等 | 区间排序 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!

