zoukankan      html  css  js  c++  java
  • 56. Merge Intervals

    Given a collection of intervals, merge all overlapping intervals.
    
    

    Example 1:

    
    
    Input: [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]
    Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
    
    
    

    Example 2:

    
    
    Input: [[1,4],[4,5]]
    Output: [[1,5]]
    Explanation: Intervals [1,4] and [4,5] are considered overlapping.
    class Solution {
        public int[][] merge(int[][] intervals) {
            int l = intervals.length;
            if(l == 0 || l == 1) return intervals;
            int[][] res = insert(new int[][]{}, intervals[0]);
                for(int i = 1; i < intervals.length; i++){
                    res = insert(res, intervals[i]);
            }
            return res;
        }
        public int[][] insert(int[][] intervals, int[] newInterval) {
            List<int[]> resu = new ArrayList();
            int s = newInterval[0], e = newInterval[1];
            int i = 0;
            //add all intervals which are before the new Interval
            while(i < intervals.length && intervals[i][1] < s){
                resu.add(intervals[i++]);
            }
            //ensure all of the intervals are merged based on the start and end time of the newInterval 
            while(i < intervals.length && intervals[i][0] <= e){
                s = Math.min(s, intervals[i][0]);
                e = Math.max(e, intervals[i][1]);
                i++;
            }
            //Add merged interval
            resu.add(new int[]{s, e});
            //Add the remaining intervals
            while(i < intervals.length) resu.add(intervals[i++]);
            int j = 0;
            int[][] res = new int[resu.size()][2];
            for(int[] tmp: resu){
                res[j++] = tmp;
            }
            return res;
        }
    }

    使用57题作为method即可,注意parameters

     
  • 相关阅读:
    狼文化的一点思考
    数据可视化之风向图
    谈谈JavaScript代码混淆
    比尔盖茨2016好书推荐
    Cesium原理篇:glTF
    个人 产品 团队(下):个人与团队
    技术 产品 团队(上):如何成为超级个体
    惊艳的HTML5动画特效及源码
    精心挑选的HTML5/CSS3应用及源码
    炫酷霸气的HTML5/jQuery应用及源码
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10412265.html
Copyright © 2011-2022 走看看