【LeetCode】 57. Insert Interval 插入区间(Hard)(JAVA)每日一题
题目地址: https://leetcode-cn.com/problems/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:
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].
Example 3:
Input: intervals = [], newInterval = [5,7]
Output: [[5,7]]
Example 4:
Input: intervals = [[1,5]], newInterval = [2,3]
Output: [[1,5]]
Example 5:
Input: intervals = [[1,5]], newInterval = [2,7]
Output: [[1,7]]
Constraints:
- 0 <= intervals.length <= 10^4
- intervals[i].length == 2
- 0 <= intervals[i][0] <= intervals[i][1] <= 10^5
- intervals is sorted by intervals[i][0] in ascending order.
- newInterval.length == 2
- 0 <= newInterval[0] <= newInterval[1] <= 10^5
题目大意
给出一个无重叠的 ,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
解题方法
1、为了方便理解,用了 List 来存
2、newInterval 和 intervals[i] 存在三种情况,分别做处理即可
- newInterval 完全大于 intervals[i]:把 newInterval 和 intervals[i] 都加入 list 中
- newInterval 完全小于 intervals[i]:只把 intervals[i] 加入 list 中
- newInterval 与 intervals[i] 有交集: newInterval 为 newInterval 与 intervals[i] 的并集,并且作为新的 newInterval 来循环
note: 后续可以优化,不用 List 来存,直接把结果放在 intervals 和 newInterval 中,减少空间复杂度,解法可以参考:【LeetCode】 57. Insert Interval 插入区间(Hard)(JAVA)
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> list = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
if (newInterval == null || intervals[i][1] < newInterval[0]) {
list.add(intervals[i]);
continue;
}
if (newInterval[1] < intervals[i][0]) {
list.add(newInterval);
list.add(intervals[i]);
newInterval = null;
continue;
}
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
}
if (newInterval != null) list.add(newInterval);
int[][] res = new int[list.size()][2];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
执行耗时:2 ms,击败了79.70% 的Java用户
内存消耗:41 MB,击败了59.78% 的Java用户