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 class Solution {
    11 private:
    12      static bool cmp(const Interval& ina,const Interval& inb){
    13         return ina.start < inb.start;
    14     }
    15     
    16 public:
    17     vector<Interval> merge(vector<Interval>& intervals) {
    18         
    19         vector<Interval> result;
    20          int count = intervals.size();
    21         if(count <= 1){
    22             return intervals;
    23         }
    24         //先按start排序 
    25         sort(intervals.begin(),intervals.end(),cmp);
    26         // 合并  三种情况
    27         result.push_back(intervals[0]);
    28       
    29        
    30         for(int i = 1;i < count;i++){
    31             Interval preIn = result.back();
    32             Interval curIn = intervals[i];
    33             if(curIn.start <= preIn.end && curIn.end > preIn.end){
    34                    preIn.end = curIn.end;
    35                    result.pop_back();
    36                    result.push_back(preIn);
    37             }
    38             else if(curIn.start > preIn.end){
    39                 result.push_back(curIn);
    40             }
    41         }
    42         return result;
    43         
    44     }
    45 };
  • 相关阅读:
    vue 兼容ie 下载文件
    IDEA maven项目添加自己的jar包依赖
    mongodb 用户权限操作
    springboot + aspect
    Enum枚举类
    线上CPU飙升100%问题排查
    Linux零拷贝技术
    Java线程池实现原理及其在美团业务中的实践
    深入解析String#intern
    Java对象内存布局
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4778521.html
Copyright © 2011-2022 走看看