• 56. Merge Intervals (JAVA)


    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.

    NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

    涉及:

    1. 数组的截取与拷贝
    2. 重写Array.sort的compare函数(注意:jdk1.7以后,必须要定义相等的情况返回0,否则会报Runtime error)
    class Solution {
        public int[][] merge(int[][] intervals) {
            if(intervals.length == 0) return intervals;
            
            Arrays.sort(intervals,0, intervals.length, new ArrayComparator());
    
            int curIndex = 0;
            for(int i = 1; i < intervals.length; i++){
                if(intervals[curIndex][1] >= intervals[i][1]){ //only reserve intervals[i-1]
                    continue;
                }
                else if(intervals[curIndex][1] >= intervals[i][0]){//integrate
                    intervals[curIndex][1] = intervals[i][1];
                }
                else{ //no interval
                    curIndex++;
                    intervals[curIndex][0] = intervals[i][0];
                    intervals[curIndex][1] = intervals[i][1];
                }
            }
            curIndex++;
            int[][] ret = new int[curIndex][2];
            System.arraycopy(intervals, 0, ret, 0, curIndex);
            
            return ret;
        }
    }
    
    class ArrayComparator implements Comparator{
        public int compare(Object o1, Object o2){
            int[] a = (int[]) o1;
            int[] b = (int[]) o2;
            if(a[0] > b[0]) return 1;//ascending order
            else if(a[0] < b[0]) return -1;
            else return 0;
        }
    }
  • 相关阅读:
    pycharm2018.1下载激活(mac平台)
    python 保存登录状态 cookie
    utf-8和utf-8-sig的区别
    AcWing 803. 区间合并
    AcWing 801. 二进制中1的个数
    AcWing 800. 数组元素的目标和
    AcWing 799. 最长连续不重复子序列
    AcWing 795. 前缀和
    AcWing 791. 高精度加法 解题记录
    九州缥缈录 合集序言
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10906135.html
Copyright © 2020-2023  润新知