zoukankan      html  css  js  c++  java
  • [LeetCode] 57.Insert Interval

    【思路】此题与56题思路相同,只是多了一个函数接口,代码如下:

     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 {
    12 public:
    13     static bool cmp(Interval &a,Interval &b)
    14     {
    15         return a.start < b.start;
    16     }
    17     vector<Interval> merge(vector<Interval>& intervals)
    18     {
    19         if(intervals.empty()) return vector<Interval> {};
    20         sort(intervals.begin(),intervals.end(),cmp);
    21         vector<Interval> res;
    22         res.push_back(intervals[0]);
    23         for(int i = 1; i < intervals.size(); i ++)
    24         {
    25             if(intervals[i].start > res.back().end)
    26                 res.push_back(intervals[i]);
    27             else
    28                 res.back().end = max(res.back().end, intervals[i].end);
    29         }
    30         return res;
    31     }
    32     vector<Interval> insert(vector<Interval>& intervals, Interval newInterval)
    33     {
    34         intervals.push_back(newInterval);
    35         vector<Interval> res = merge(intervals);
    36         return res;
    37     }
    38 };
  • 相关阅读:
    BZOJ3631 [JLOI2014] 松鼠的新家
    HDU
    HDU
    HDU
    二分图求最大独立集模板
    HDU
    HDU
    HDU
    Codeforces 1197F Coloring Game 矩阵快速幂 (看题解)
    HDU
  • 原文地址:https://www.cnblogs.com/lca1826/p/6406734.html
Copyright © 2011-2022 走看看