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);
  • 相关阅读:
    在Idea中使用Eclipse编译器
    Idea切换svn分支,类似Eclipse的Switch功能
    Spring AOP详解
    CGLib动态代理原理及实现
    IDEA下搜狗输入法输入中文时卡着不动的参考解决方法
    Nginx反向代理丢失cookie的问题
    redis连接池自动释放
    Redis常用命令
    waitpid之status意义解析
    bash中管道命令返回值如何确定(下)
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6362250.html
Copyright © 2011-2022 走看看