/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: // 错误: 没想到排序的问题, 导致案例报错 ,我们利用map排序 没想到map覆盖问题 vector<Interval> merge(vector<Interval>& intervals) { vector<Interval> ans; if (intervals.empty()) return ans; // 首先要进行一个排序的操作 解决现在的问题, 利用map的自动排序功能进行排序 // 忽视了同一个key值的覆盖问题 map<int, int> m; for (auto item : intervals) { m[item.start] = max(m[item.start], item.end); // 这里进行了同一个区间合并 } // for (auto item : m) { // cout << "[ " << item.first << "," << item.second << " ]" << endl; // } // cout << "---------------------" << endl; // 首先把第一个区间放进去. auto it = m.begin(); ans.push_back(Interval(it->first, it->second)); // 核心思想: 依次遍历, 判断当前的和在数组中的那个, 这两个interval是否重合, 如果重合, 我们对其进行合并 // 如果不重合, 不作处理 it++; for (; it != m.end(); it++) { // 先把ans中最后个一个拿出来 Interval tmp = ans.back(); if (max(tmp.start, it->first) <= min(tmp.end, it->second)) { // 如果重合了, 之前的就没用了,先把之前的那个抛出去, 然后把重合的结果放进来 ans.pop_back(); ans.push_back(Interval(min(tmp.start, it->first), max(tmp.end, it->second))); cout << "show ---" << endl; } // 如果没重合 else { ans.push_back(Interval(it->first, it->second)); } } // for (auto item : ans) { // cout << "[ " << item.start << "," << item.end << " ]" << endl; // } return ans; } };
leetcode56 合并区间
猜你喜欢
转载自blog.csdn.net/weixin_36149892/article/details/80291536
今日推荐
周排行