zoukankan      html  css  js  c++  java
  • 插入区间

    package Leetcode;
    
    import java.util.Arrays;
    
    /**
     * 给出一个无重叠的 ,按照区间起始端点排序的区间列表。
    在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
     */
    /**
     * 思路:1.从左到右找到第一个新区间位置,他可以是与新区间的左边交叉,也可以是最后一个完全在新区间左边的区间
     *       2. 找到左边位置后找右边放的位置,遍历找到后面的一个区间,左边大于等于新区间的右边,对于中间的区间,重置新区间,左边是中间节点中最小左,右边是最大右,直到左边完全大于新区间
     *       3.新区间插入,右边完全相离插入
     */
    public class insertQujian {
        public static void main(String[] args) {
            int [][]intervals={{1,3},{6,9}};
            int []newInterval={2,5};
            int [][]result=insert(intervals, newInterval);
            int x=0;
        }
        public static int[][] insert(int[][] intervals, int[] newInterval) {
            if(intervals==null||intervals.length==0){
                int [][]result={newInterval};
                return result;
            }
            int res[][]=new int[intervals.length+1][2];
            int i=0;
            int idx=0;
            while(i<intervals.length&&intervals[i][1]<newInterval[0]){
                res[idx++]=intervals[i++];
            }
            while(i<intervals.length&&intervals[i][0]<=newInterval[1]){
                newInterval[0]=Math.min(intervals[i][0],newInterval[0]);
                newInterval[1]=Math.max(intervals[i][1],newInterval[1]);
                i++;
            }
            res[idx++]=newInterval;
            while(i<intervals.length){
                res[idx++]=intervals[i++];
            }
            
            
            return Arrays.copyOf(res, idx);
        }
        
    }
  • 相关阅读:
    Vasya and Endless Credits CodeForces
    Dreamoon and Strings CodeForces
    Online Meeting CodeForces
    数塔取数 基础dp
    1001 数组中和等于K的数对 1090 3个数和为0
    1091 线段的重叠
    51nod 最小周长
    走格子 51nod
    1289 大鱼吃小鱼
    POJ 1979 Red and Black
  • 原文地址:https://www.cnblogs.com/jieyi/p/14056295.html
Copyright © 2011-2022 走看看