zoukankan      html  css  js  c++  java
  • [Leetcode 84] 56 Merge Intervals

    Problem:

    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].

    Analysis:

    First sort the vector according to the start time of each interval. Then scan through the vector, if the current interval's start time is between the former interval's strart and end time, we need to merge them. The newly merged interval's start is the former interval's start, but the end should be the max{current.end, former.end}.

    To speed up this process, use an extra result vector to store the final result rather than using vector.erase method on original method.

    Code:

     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 cmpA(const Interval& a, const Interval& b)
    12 {
    13     return a.start < b.start;
    14 }
    15 
    16 class Solution {
    17 public:
    18     vector<Interval> merge(vector<Interval> &intervals) {
    19         // Start typing your C/C++ solution below
    20         // DO NOT write int main() 
    21         vector<Interval> res;
    22         sort(intervals.begin(), intervals.end(), cmpA);
    23 
    24         Interval tmp = intervals[0];
    25         for (int i=1; i<intervals.size(); i++) {
    26             if (tmp.start <= intervals[i].start &&
    27                 tmp.end >= intervals[i].start) {
    28                     tmp.end = max(intervals[i].end, tmp.end);
    29             }
    30             else {
    31                 res.push_back(tmp);
    32                 tmp = intervals[i];
    33             }
    34         }
    35 
    36         return res;
    37     }
    38     
    39     int max(int a, int b) {
    40         return (a>b)? a : b;
    41     }
    42 };
    View Code
  • 相关阅读:
    Win32程序支持命令行参数的做法
    打包jar类库与使用jar类库
    Java日期格式化
    集合类层次结构关系
    深入理解Arrays.sort()
    Java 异常类层次结构
    equals()与hashCode()方法协作约定
    shp数据和tab数据的两点区别
    java+上传文件夹
    vue+大文件分片上传
  • 原文地址:https://www.cnblogs.com/freeneng/p/3210450.html
Copyright © 2011-2022 走看看