标签:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9]
, insert and merge [2,5]
in as [1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge [4,9]
in as [1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
思路:在list中删除在start和end之间的元素,如果start,或end在某一元素的start和end之间,删除该元素,调整插入元素的start或end值。最后将所需插入的元素插入合适的位置。思想很简单,细节上调了很久,很坑的一题。
/** * 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; } * } */ public class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval) { int n=intervals.size(); int index=0; for(int i=0;i<n;i++){ Interval temp=null; temp=intervals.get(i); if(newInterval.start>=temp.start&&newInterval.end<=temp.end){ return intervals; }else if(newInterval.start>=temp.start&&newInterval.start<=temp.end){ newInterval.start=temp.start; intervals.remove(i); index=i; n--; i--; }else if(temp.start>newInterval.start&&temp.end<newInterval.end){ intervals.remove(i); index=i; n--; i--; }else if(newInterval.end>=temp.start&&newInterval.end<=temp.end){ newInterval.end=temp.end; intervals.remove(i); index=i; n--; i--; } } if(n==0){ intervals.add(newInterval); return intervals; } if(newInterval.end<intervals.get(0).start){ intervals.add(0,newInterval); return intervals; }else if(newInterval.start>intervals.get(n-1).end){ intervals.add(newInterval); return intervals; } for(int j=0;j<n-1;j++){ Interval temp1=intervals.get(j); Interval temp2=intervals.get(j+1); if(temp1.end<newInterval.start&&temp2.start>newInterval.end){ intervals.add(j+1,newInterval); } } return intervals; } }
标签:
原文地址:http://www.cnblogs.com/gonewithgt/p/4566524.html