• Merge Intervals


    1. Title

    Merge Intervals

    2. Http address

    https://leetcode.com/problems/merge-intervals/

    3. The question

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

    4 My code(AC)

    •  
       1 // Accepted
       2       public static List<Interval> merge(List<Interval> intervals) {
       3          
       4           List<Interval> res = new ArrayList<Interval>();
       5           if ( intervals == null || intervals.isEmpty() )
       6               return res;
       7           
       8           Comparator<Interval> com = new Comparator<Interval>(){
       9                   public int compare(Interval a ,Interval b)
      10                   {
      11                       if ( a.start < b.start) return -1;
      12                       else if ( a.start > b.start ) return 1;
      13                       else {
      14                           if ( a.end < b.end) return -1;
      15                           else if ( a.end > b.end ) return 1;
      16                           else return 0;
      17                       }
      18                   }
      19           };
      20           
      21           Collections.sort(intervals,com);
      22           
      23           for( int i = 0 ; i < intervals.size(); i++)
      24           {
      25               Interval cur = intervals.get(i);
      26               if ( res.isEmpty() )
      27               {
      28                   res.add(cur);
      29               }else{
      30                   Interval last = res.get(res.size() - 1);
      31                   if ( last.end >= cur.start)
      32                   {
      33                       last.end = Math.max(last.end, cur.end);
      34                   }else{
      35                       res.add(cur);
      36                   }
      37               }
      38           }
      39           return res;
      40         }
      41       
  • 相关阅读:
    linux 6 安装 Nagios服务
    linux 6 安装 Nginx服务
    Rsync的配置与使用
    linux 6 搭建 msyql 服务
    linux6搭建Apache服务
    Linux 7搭建NFS服务
    Linux 6 忘记root密码重置
    简单makefile
    多线程c++11编程题目
    redis 代码结构与阅读顺序
  • 原文地址:https://www.cnblogs.com/ordili/p/4970052.html
Copyright © 2020-2023  润新知