zoukankan      html  css  js  c++  java
  • 56. 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  * public class 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 public class Solution {
    11     public List<Interval> merge(List<Interval> intervals) {
    12         if(intervals.size()<2) return intervals;
    13         // sort by ascending start pointer by using annoymous comparator
    14         //intervals.sort((i1,i2)->Integer.compare(i1.start,i2.start));
    15         Comparator<Interval> comp = new Comparator<Interval>(){
    16             public int compare(Interval i1,Interval i2){
    17                 return i1.start-i2.start;
    18             }
    19         };
    20         Collections.sort(intervals,comp);
    21         int start = intervals.get(0).start;
    22         int end = intervals.get(0).end;
    23         // store the result Interval list
    24         List<Interval> result = new ArrayList<>();
    25         for(Interval interval:intervals){
    26             if(interval.start<=end){
    27                 // overlapping intervals,move the end if needed
    28                 end = Math.max(end,interval.end);
    29             }else{
    30                 //Disjoint interval, add the previous one and reset the bounds
    31                 result.add(new Interval(start,end));
    32                 start = interval.start;
    33                 end = interval.end;
    34             }
    35         }
    36         result.add(new Interval(start,end));
    37         return result;
    38     }
    39 }
    40 //as for the run time complexity ,sort time costs nlogn time. compare the intervals and put it into result costs O(n) time ,so the total run time could be nlogn,the space complexity would be O(n);
  • 相关阅读:
    C# webservice服务跟踪调试方法(转)
    ServiceBase.OnStart 方法
    基本类型和引用类型
    js基本概念
    在HTML中使用JavaScript
    js中的this
    SQL 取两日期的记录
    常用数据结构[转]
    How to: Pass Values Between ASP.NET Web Pages
    example for store procedure with both transcration and error handling
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6362250.html
Copyright © 2011-2022 走看看