Leecode57 intervalo de inserción

Descripción del título

Dado un conjunto de intervalos de tiempo que no se superponen, inserte un nuevo intervalo de tiempo en el intervalo de tiempo (si hay superposición, combine los intervalos).
Estos intervalos de tiempo se ordenan inicialmente según su hora de inicio.
Ejemplo 1:
Dado un intervalo de tiempo [1,3], [6,9], inserte un intervalo de tiempo [2,5] en estos dos intervalos de tiempo, y combínelo con el intervalo de tiempo original para convertirse en [1] , 5], [6,9]
Ejemplo 2:
intervalo de tiempo dado [1,2], [3,5], [6,7], [8,10], [12,16], en estos momentos Inserte el intervalo de tiempo [4,9] en el intervalo y combínelo con el intervalo de tiempo original para convertirse en [1,2], [3,10], [12,16].
Esto se debe a que el intervalo de tiempo [4, 9] cubre el intervalo de tiempo [3,5], [6,7], [8,10].

código java

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
        ArrayList <Interval> res = new ArrayList<>();
        if(intervals == null){
            return res;
        }
        int i =0;
        int n = intervals.size();
        int start = newInterval.start;
        int end = newInterval.end;
       //不能取等号,这是把 newInterval 之前的所有都放进res
        while(i < n && intervals.get(i).end < start){
            res.add(intervals.get(i));      
            i++;
        }
        //存在一种情况 newInterval在这些线段之后
        if(i == n){
            res.add(newInterval);
            return res;
        }
        //到这一步 说明 newInterval 有一个合适的融合位置
        start = Math.min(start,intervals.get(i).start);
        //待插入线段的end坐标 
        int endn = end;
        while(i < n && intervals.get(i).start <= endn){
            end = Math.max(end,intervals.get(i).end);
            i++;
        }        
        res.add(new Interval(start,end));
        //将右侧剩余的加入
        while(i < n){
            res.add(intervals.get(i));
            i++;
        }
        return res;
        
    }
}
Publicado 72 artículos originales · gustó 0 · 725 visitas

Supongo que te gusta

Origin blog.csdn.net/weixin_40300702/article/details/105437451
Recomendado
Clasificación