• 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     @SuppressWarnings("unchecked")
    12     public static List<Interval> partMerge(List<Interval> intervals){
    13         intervals.sort(new Comparator(){
    14             @Override
    15             public int compare(Object o1, Object o2) {
    16                 Interval i1 = (Interval)o1;
    17                 Interval i2 = (Interval)o2;
    18                 if(i1.start!=i2.start)
    19                     return i1.start-i2.start;
    20                 else
    21                     return (Math.abs(i1.end-i1.start)-Math.abs(i2.end-i2.start));
    22             }
    23         });
    24         
    25         List<Integer> removeList = new ArrayList<Integer>();
    26         for(int i = 0;i < intervals.size()-1; i++ )
    27             if(intervals.get(i).end>=intervals.get(i+1).start&&intervals.get(i).end<=intervals.get(i+1).end){
    28                     intervals.get(i+1).start = intervals.get(i).start;
    29                     removeList.add(i);
    30             }else if(intervals.get(i).end>=intervals.get(i+1).end){
    31                 intervals.get(i+1).end = intervals.get(i).end;
    32                 intervals.get(i+1).start = intervals.get(i).start;
    33                 removeList.add(i);
    34             }
    35         for(int i = removeList.size()-1; i>=0 ; i--){
    36             intervals.remove(intervals.get(removeList.get(i)));
    37         }
    38         return intervals;
    39     }
    40     public List<Interval> merge(List<Interval> intervals) {
    41         int presize = 0;
    42         do{
    43             presize = intervals.size();
    44             intervals = partMerge(intervals);
    45         }while(presize!=intervals.size());
    46         return intervals;
    47     }
    48 }
  • 相关阅读:
    [原创]二路归并排序针对数组的场景(C++版)
    [原创]装饰模式(java版)
    [原创]Java中Map根据值(value)进行排序实现
    [原创]适配器模式(java版)
    信了你的邪
    String和Date转换
    电商运营面试题
    springCloud发送请求多对象参数传递问题
    JS实现页面以年月日时分秒展示时间
    java三种注释以及参数涵义(转)
  • 原文地址:https://www.cnblogs.com/lxk2010012997/p/6414893.html
Copyright © 2020-2023  润新知