zoukankan      html  css  js  c++  java
  • [LeetCode] Merge Intervals

    Given a collection of intervals, merge all overlapping intervals.

    For example,
    Given [1,3],[2,6],[8,10],[15,18],
    return [1,6],[8,10],[15,18].

     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 
    11 bool comp(const Interval &lhs, const Interval &rhs)
    12 {
    13     return lhs.start < rhs.start;
    14 }
    15 
    16 class Solution {
    17 private:
    18     vector<Interval> ret;
    19 public:
    20     vector<Interval> merge(vector<Interval> &intervals) {
    21         // Start typing your C/C++ solution below
    22         // DO NOT write int main() function
    23         ret.clear();
    24         
    25         sort(intervals.begin(), intervals.end(), comp);
    26         for(int i = 0; i < intervals.size(); i++)
    27             if (ret.size() == 0)
    28                 ret.push_back(intervals[i]);
    29             else
    30             {
    31                 int size = ret.size();
    32                 if (ret[size-1].start <= intervals[i].start && intervals[i].start <= ret[size-1].end)
    33                     ret[size-1].end = max(ret[size-1].end, intervals[i].end);
    34                 else
    35                     ret.push_back(intervals[i]);
    36             }
    37             
    38             
    39         return ret;
    40     }
    41 };
  • 相关阅读:
    Struts2_模块包含
    Struts2_访问Web元素
    Struts2_简单数据验证
    获取当前日期
    iOS NSMutableArray添加NSInteger元素
    iOS label换行 自适应
    iOS高德地图自定义annotation添加不同图片
    @property(nonatomic) UIViewAutoresizing autoresizingMask;
    HTML
    图片压缩
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787387.html
Copyright © 2011-2022 走看看