标签:style blog class code java tar
区间合并,贪心,需要注意边界情况,LeetCode的数据还是比较好的,这样才能写出健壮的程序。
附上代码:
1 /**
2 * Definition for an interval.
3 * struct Interval {
4 * int start;
5 * int end;
6 * Interval() : start(0), end(0) {}
7 * Interval(int s, int e) : start(s), end(e) {}
8 * };
9 */
10 class Solution {
11 public:
12 vector<Interval> merge(vector<Interval> &intervals) {
13 typedef pair<int, int> pii;
14 vector<pii> my_pair;
15 for (unsigned int i = 0; i < intervals.size(); i++) {
16 my_pair.push_back(pii(intervals[i].start, intervals[i].end));
17 }
18 sort(my_pair.begin(), my_pair.end());
19 vector<Interval> ans;
20 //输入为空
21 if (intervals.size() == 0) {
22 return ans;
23 }
24 int beg = my_pair[0].first, ed = my_pair[0].second;
25 for (unsigned int i = 1; i < my_pair.size(); i++) {
26 if (my_pair[i].first <= ed) {
27 ed = max(my_pair[i].second, ed);
28 } else {
29 ans.push_back(Interval(beg, ed));
30 beg = my_pair[i].first;
31 ed = my_pair[i].second;
32 }
33 }
34 //处理最后一个数据
35 if (ans.size() == 0 || beg > ans[ans.size()-1].start) {
36 ans.push_back(Interval(beg, ed));
37 }
38
39 return ans;
40 }
41 };
LeetCode---Merge Intervals,布布扣,bubuko.com
标签:style blog class code java tar
原文地址:http://www.cnblogs.com/Stomach-ache/p/3704485.html