zoukankan      html  css  js  c++  java
  • LeetCode---Merge Intervals

    题目链接

    区间合并,贪心,需要注意边界情况,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 };
  • 相关阅读:
    c# 指针unsafe/fixed -- 【一】
    Windows消息大全(转)
    Windows消息过滤
    C#预编译
    c#摄像头编程实例 (转)
    多线程按顺序执行 (转)
    定位程序集
    无需写try/catch,也能正常处理异常 (转)
    无需Try catch 的UI事件封装类
    注册表修改安全策略
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3704485.html
Copyright © 2011-2022 走看看