题目
leetcode的每日一题,看到是hard有些慌,但是看题目似乎并不难; 有两种想法,在本地空间对intervals进行修改,或新建vector来插入
本地修改的方法需要做很多判断,而且需要在本地vector进行多次erase操作,效率并不会比新建vector效率高!
本地修改代码(要是遇到很多需要合并的单元会导致很多erase操作,很耗时!):
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
int count = 0;
if(intervals.size()>0){
if((intervals.front())[0]>newInterval[0] && (intervals.back())[1]<newInterval[1]){
// 用于应对测试用例中最后一个超长输入
// 这也是直接在intervals上操作的坏处,要是intervals有很多需要合并的单元,那么需要很多次erase,容易导致超时!
vector<vector<int>> res;
res.push_back(newInterval);
return res;
}
}
for(vector<vector<int>>::iterator iter=intervals.begin();iter!=intervals.end();){
if(newInterval[1]<(*iter)[0]){
// newInterval在左侧
if(count == 0){
intervals.insert(iter,newInterval);
count ++;
}
return intervals;
}
else{
if(newInterval[0]>(*iter)[1]){
// newInterval在右侧
iter++;
continue;
}
else{
// 有交集
int left = min((*iter)[0],newInterval[0]);
int right = max((*iter)[1],newInterval[1]);
intervals.erase(iter);
newInterval = {left,right};
}
}
}
if(count == 0)
intervals.push_back(newInterval);
return intervals;
}
};
新建vector:
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
int count = 0;
for(int i=0;i<intervals.size();i++){
if(newInterval[1]<intervals[i][0]){
// newInterval在左侧,且无交集
if(count == 0){
res.push_back(newInterval);
count++;
}
res.push_back(intervals[i]);
}
else{
if(newInterval[0]>intervals[i][1]){
// newInterval在右侧,且无交集
res.push_back(intervals[i]);
}
else{
// 有交集
int left = min(newInterval[0],intervals[i][0]);
int right = max(newInterval[1],intervals[i][1]);
newInterval = {left,right};
}
}
}
if(count == 0)
res.push_back(newInterval);
return res;
}
};
本文针对LeetCode上的一个较难的问题提供了两种解决方案。一种是在原始数据结构上直接进行修改,但可能会因为频繁的删除操作而导致效率低下;另一种是通过创建新的数据结构来避免这一问题,并详细解释了每种方法的具体实现步骤。
156

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



