• 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

     
  • 相关阅读:
    jquery on()方法绑定多个选择器,多个事件
    html中常用的特殊符号(转)
    jQuery自定义动画,animate()包装器方法
    纯CSS下拉菜单
    DIV水平居中的几种方法
    OOXML是什么
    Chrome网络工具总结
    Content-Length错误导致的Servlet下载文件失败问题
    Fiddler操作总结
    WinSCP上传下载过滤指定目录和文件
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10412265.html
Copyright © 2020-2023  润新知