1. 程式人生 > >【leetcode】57. (Hard) Insert Interval

【leetcode】57. (Hard) Insert Interval

題目連結


解題思路:
假設intervals是由很多blocks組成的,把這些blocks分成三個部分,一個是end的值都小於newInterval.start的部分,一個是和newInterval有重疊的部分,然後是start的值都大於newInterval.end的部分。

先將第一、三個部分求出來,分別放到headResult和tailResult中,然後判斷一下中間部分和block之間的重疊情況即可。


提交程式碼:

class Solution {
    public List<Interval> insert(List<Interval>
intervals, Interval newInterval) { List<Interval> headResult=new ArrayList<Interval>(); List<Interval> tailResult=new ArrayList<Interval>(); List<Interval> res=new ArrayList<Interval>(); Interval midResult=new Interval(); if(intervals==null||
intervals.size()==0) { res.add(newInterval); return res; } int newIntervalStart,newIntervalEnd; //find the start position of the overlap for(newIntervalStart=0;newIntervalStart<intervals.size();newIntervalStart++) { if(intervals.get(newIntervalStart).end<
newInterval.start) headResult.add(intervals.get(newIntervalStart)); else break; } //check the relative position of head block and newInterval boolean headInBlock=false; if(newIntervalStart<intervals.size()&& newInterval.start>intervals.get(newIntervalStart).start) headInBlock=true; //find the end position of the overlap for(newIntervalEnd=intervals.size()-1;newIntervalEnd>=0;newIntervalEnd--) { if(intervals.get(newIntervalEnd).start>newInterval.end) tailResult.add(intervals.get(newIntervalEnd)); else break; } //check the relative position of tail block and newInterval boolean tailInBlock=false; if(newIntervalEnd>=0&& intervals.get(newIntervalEnd).end>newInterval.end) tailInBlock=true; //check the midResult if(headInBlock) midResult.start=intervals.get(newIntervalStart).start; else midResult.start=newInterval.start; if(tailInBlock) midResult.end=intervals.get(newIntervalEnd).end; else midResult.end=newInterval.end; //Combine the head,mid and tail result res.addAll(headResult); res.add(midResult); for(int i=tailResult.size()-1;i>=0;i--) res.add(tailResult.get(i)); return res; } }

執行結果:
在這裡插入圖片描述