• 57. Insert Interval


    June-19-2019
    主要思路是,merge all intervals that have overlap with being-inserted interval
    Edge case比较麻烦。

    • 有可能合并完没有剩下的了,要插入的变成了最后一个,没插入,所以最后要多插入一下
    • 有可能合并完还有剩下的,剩下可以按部就班都插入进去,所以最后不需要多插入一下
      解决这2个CASE的方法就是,第二种的情况下,插入,然后更新待插入的。。这样总会剩下一个。
        public int[][] insert(int[][] intervals, int[] newInterval) {
            if (intervals.length == 0) {
                return new int[][]{newInterval};
            }
    
            List<int[]> tempList = new ArrayList<>();
            for (int i = 0; i < intervals.length; i ++) {
                int[] temp = intervals[i];
                if (temp[1] < newInterval[0]) {
                    tempList.add(temp);
                } else if (temp[0] > newInterval[1]) {
                    // from now on, there won't be any overlaps. 这样不停更新newInterval的好处是,最后会少加1个,因为
                    // 下面ELSE的有一个情况是,一直MERGE到最后,并没有加到tempList里,这样的好处是保持一直,总有最后一个newInterval没加
                    // 换一种想法其实就是,第一个if之后,当做merge interval重新做了一遍。。 
                    tempList.add(newInterval);
                    newInterval = temp;
                } else {
                    // start to encounter overlap, merge all overlaps, newInterval will eventually become merged result
                    newInterval[0] = Math.min(temp[0], newInterval[0]);
                    newInterval[1] = Math.max(temp[1], newInterval[1]);
                }
            }
            int[][] res = new int[tempList.size() + 1][2];
            for (int i = 0; i < tempList.size(); i++) {
                res[i] = tempList.get(i);
            }
            res[tempList.size()] = newInterval;
            return res;
        }
    
  • 相关阅读:
    amoeba连接mysql--ERROR 2006 (HY000): MySQL server has gone away
    fd最大值和限制
    mysql ab主从复制出错及解决过程
    mysql复制知识整理
    MySQL权限
    客户端用plsql进行中文条件查询时无结果的解决办法
    ORACLE ASH/AWR
    总结:常用的Linux系统监控命令(2)
    讨论几种数据列Column的特性(上)
    Spring核心技术(五)——Spring中Bean的作用域
  • 原文地址:https://www.cnblogs.com/reboot329/p/5891278.html
Copyright © 2020-2023  润新知