题目链接:leetcode.
/*
执行用时:12 ms, 在所有 C++ 提交中击败了99.61%的用户
内存消耗:13.9 MB, 在所有 C++ 提交中击败了43.21%的用户
*/
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int N = intervals.size();
if(N < 2)
return intervals;
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
ans.push_back(intervals[0]);
for(int i = 1;i < N;++i)
{
int a = intervals[i][0], b = intervals[i][1];
int update = 0;
for(int j = 0;j < ans.size() && update == 0;++j)
{
//两个集合的关系
if(b < ans[j][0] || a > ans[j][1])
{
continue;
}
else if(b == ans[j][0])
{
ans[j][0] = a;
}
else if(a == ans[j][1])
{
ans[j][1] = b;
}
else
{
ans[j][0] = min(a, ans[j][0]);
ans[j][1] = max(b, ans[j][1]);
}
update = 1;
}
if(!update)
{
ans.push_back({a, b});
}
}
return ans;
}
};
写复杂了
如果当前区间的左端点在数组 ans 中最后一个区间的右端点之后,那么它们不会重合,我们可以直接将这个区间加入数组 ans 的末尾;
否则,它们重合,我们需要用当前区间的右端点更新数组 ans 中最后一个区间的右端点,将其置为二者的较大值。
/*
执行用时:24 ms, 在所有 C++ 提交中击败了63.58%的用户
内存消耗:13.8 MB, 在所有 C++ 提交中击败了67.21%的用户
*/
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int N = intervals.size();
if(N < 2)
return intervals;
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
ans.push_back(intervals[0]);
for(int i = 1;i < N;++i)
{
int a = intervals[i][0], b = intervals[i][1];
if(a > ans.back()[1])
{
ans.push_back({a, b});
}
else
{
ans.back()[1] = max(ans.back()[1], b);
}
}
return ans;
}
};
437

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



