leetcode Merge Intervals
思路:
以区间的左边为键值, 对区间进行排序 然后找出重复的部分, 如果重复就判断是否需要更新区间 如果没有重复就将当前的区间加入到 vector 中
/** * 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: static bool cmp(Interval a, Interval b) { return a.start < b.start; } vector<Interval> merge(vector<Interval> &intervals) { int size = intervals.size(); if (size == 0 || size == 1) return intervals; sort(intervals.begin(), intervals.begin()+size, cmp); vector <Interval> new_vec; int start = intervals[0].start; int end = intervals[0].end; for (int i = 1; i < size; i++) { if (intervals[i].start <= end) { // 如果可以合并 if (end < intervals[i].end) { // 判断是否要增大右边 end = intervals[i].end; } } else { new_vec.push_back(Interval(start, end)); // 比区间的左边小, 直接加入到集合中 start = intervals[i].start; end = intervals[i].end; } } new_vec.push_back(Interval(start, end)); // 最后一个区间的时候我们已经退出循环 return new_vec; } };
// CreateTime: 2015-04-22 22:19:00 #include <isotream> #include <cstdio> #include <algorithm> using namespace std; typedef pair<int, int> Interval; bool cmp(Interval a, Interval b) { return a.first < b.first; } int main(void) { vector<Interval> interval; // interval.push_back(make_pair(1, 4)); // interval.push_back(make_pair(1, 4)); interval.push_back ( make_pair (1, 3)); interval.push_back ( make_pair (2, 6)); interval.push_back ( make_pair (5, 7)); interval.push_back ( make_pair (8, 10)); interval.push_back ( make_pair (9, 12)); interval.push_back ( make_pair (11, 18)); int size = interval.size(); sort(interval.begin(), interval.begin()+size, cmp); vector <Interval> new_vec; int start = interval[0].first; int end = interval[0].second; for (int i = 1; i < size; i++) { if (interval[i].first <= end) { if (end < interval[i].second) { end = interval[i].second; } } else { new_vec.push_back(Interval(start, end)); start = interval[i].first; end = interval[i].second; } } new_vec.push_back(Interval(start, end)); int size_2 = new_vec.size(); for (int i = 0; i < size_2; i++) { printf("%d %d\n", new_vec[i].first, new_vec[i].second); } return 0; }