[LeetCode] 57. Insert Interval
来源:互联网 发布:js下载选择文件夹路径 编辑:程序博客网 时间:2024/06/11 21:50
题目链接: https://leetcode.com/problems/insert-interval/description/
Description
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]
.
解题思路
题意大致为在一个已经排序过的相互无交集的区间数组中,添加一个新的区间,将有交集的区间全部合并成一个新的区间。
题目不是很难,注意下细节就可以了。遍历初始区间数组,对每一个区间判断与目标区间是否有交集,交集的判定可以归结为三种,两种括号表示两个不同的区间
(---<--)--->
<---(-->---)
<---(--)--->
有交集的区间个数可以通过另一个迭代器来记录,每发现一个区间有交集迭代器就加一,直到无交集或者到达数组末尾为止,删除该数组区间,再在此位置插入新的区间。
另外,还要考虑新区间与原来数组中的区间都没有交集的情况。通过比较新区间的 end
是否小于该轮第一个区间的 start
来判断是否有交集,涵盖了每个原数组区间前面的空隙,不包括最后一个区间后面的间隙,因此还要单独比较新区间 start
和原数组中最后一个区间的 end
。
Code
class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { if (intervals.empty()) { intervals.push_back(newInterval); } else { for (auto it = intervals.begin(); it != intervals.end(); ++it) { auto eit = it; int start = newInterval.start; int end = newInterval.end; while (eit != intervals.end()) { if ((start <= eit->end && start >= eit->start) || (end >= eit->start && end <= eit->end) || (start <= eit->start && end >= eit->end)) { start = min(start, eit->start); end = max(end, eit->end); eit++; } else { break; } }; if (eit != it || end < it->start) { it = intervals.erase(it, eit); intervals.insert(it, Interval(start, end)); break; } else if (it + 1 == intervals.end() && start > it->end) { intervals.insert(it + 1, Interval(start, end)); break; } } } return intervals; }};
- LeetCode --- 57. Insert Interval
- [Leetcode] 57. Insert Interval
- [LeetCode]57.Insert Interval
- [leetcode] 57.Insert Interval
- [leetcode] 57.Insert Interval
- Leetcode 57. Insert Interval
- LeetCode 57. Insert Interval
- LeetCode 57. Insert Interval
- [LeetCode] 57. Insert Interval
- [Leetcode]57. Insert Interval
- leetcode 57. Insert Interval
- leetcode 57.Insert Interval
- leetcode-57. Insert Interval
- leetcode 57. Insert Interval
- Leetcode-57. Insert Interval
- 【LeetCode】57. Insert Interval
- LeetCode 57. Insert Interval
- leetcode 57. Insert Interval
- Git使用积累
- Solidity 数组 (Arrays)
- 陶陶摘苹果
- 习题6.7
- ThinkPHP5.0---------请求和响应
- [LeetCode] 57. Insert Interval
- 登录注册判断密码再次输入
- 最长递增子序列
- JavaScript 通过字符串获取function
- pyhon实现决策树(ID3)算法进行数据的分类预测
- express---处理请求
- 判断窗口是否退出
- 杨辉三角
- AJAX数据格式之JSON