zoukankan      html  css  js  c++  java
  • 【leetcode】Merge Intervals

    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 public:
    12     vector<Interval> merge(vector<Interval> &intervals) {
    13         vector<Interval> result;
    14         if(intervals.empty()) return result;
    15        
    16         sort(intervals.begin(),intervals.end(),cmp);
    17        
    18         int start=intervals[0].start;
    19         int end=intervals[0].end;
    20        
    21         for(int i=1;i<intervals.size();i++)
    22         {
    23             if(intervals[i].start<=end)
    24             {
    25                 //注意[1,4],[2,3]的情况
    26                 end=end<intervals[i].end?intervals[i].end:end;
    27             }
    28             else
    29             {
    30                 result.push_back(Interval(start,end));
    31                 start=intervals[i].start;
    32                 end=intervals[i].end;
    33             }
    34         }
    35  
    36         result.push_back(Interval(start,end));
    37         return result;
    38     }
    39    
    40     static int cmp(const Interval &a,const Interval &b)
    41     {
    42         if(a.start<b.start) return 1;
    43         else if(a.start>b.start) return 0;
    44         else return a.end<b.end;
    45     }
    46 };
  • 相关阅读:
    day 24
    day23
    day 22
    java中空格的操作
    java 解析Word文档以及Excel表格数据带有图片(2003/2007)
    java中创建文件夹
    http请求问题
    js弹框显示全部内容
    java实现HTTP请求的三种方式
    solr与java整合使用
  • 原文地址:https://www.cnblogs.com/reachteam/p/4209522.html
Copyright © 2011-2022 走看看