zoukankan      html  css  js  c++  java
  • leetcode--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].

    public class Solution {
        /**There is not special algorithm for this problem.<br>
    	 * 1. sort the intervals according to the start point
    	 * 2. linear scan the sorted intervals and then merge them together
    	 * 
    	 * @param intervals --List of Intervals.
    	 * @return --List of Intervals, in which no intervals have overlaps 
    	 * @author Averill Zheng
    	 * @version 2014-06-12--world cup opening day
    	 * @since JDK 1.7
    	 */
        public List<Interval> merge(List<Interval> intervals) {
            List<Interval> result = new ArrayList<Interval>();
    		if(!intervals.isEmpty()){
    			Collections.sort(intervals, new IntervalComparator());
    			int length = intervals.size();
    			int start = intervals.get(0).start;
    			int end = intervals.get(0).end;
    			for(int i = 1; i < length; ++i){
    				Interval current = intervals.get(i);
    				if(current.start <= end)
    					end = Math.max(end, current.end);
    				else{
    					result.add(new Interval(start, end));
    					start = current.start;
    					end = current.end;
    				}
    			}
    			result.add(new Interval(start, end));
    		}
    		return result;
    	}
    }
    
    class IntervalComparator implements Comparator<Interval>{
    	public int compare(Interval a, Interval b){
    		return Integer.compare(a.start, b.start);
    	}
    }
    

      

  • 相关阅读:
    SQL 表连接
    SQL 时间日期函数
    SQL 转换函数
    25 -2 正则爬虫例子
    25 -1 正则 re模块 (findall、search、match、sub、subn、split、compile、finditer)
    25 python 常用模块
    24- 1 模块
    23-8 python模块定义
    23-5 面试题:1000个员工,我们认为名字和年龄相等,就为同一个人
    23-4 __eq__方法
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3785015.html
Copyright © 2011-2022 走看看