zoukankan      html  css  js  c++  java
  • 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       
  • 相关阅读:
    C#设计模式学习笔记-单例模式
    面向对象的七种设计原则
    继承 示例1
    继承和多态的那些事
    体检套餐管理项目
    魔兽登录系统
    清空表
    mysql批量插入
    mkdir用大括号同时建立多个同级和下级目录
    linux查看机器位数
  • 原文地址:https://www.cnblogs.com/ordili/p/4970052.html
Copyright © 2011-2022 走看看