/**
* 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) {
List<Interval> list = new ArrayList<>();
for (int i=0;i<intervals.size();i++){
//第一种情况是插入的这个东西在他的右边
if (newInterval.start>intervals.get(i).end){
list.add(intervals.get(i));
//在他的左边
}else if (newInterval.end<intervals.get(i).start){
list.add(newInterval);
newInterval = new Interval(intervals.get(i).start,intervals.get(i).end);
//刚好相交了
}else if (newInterval.start<=intervals.get(i).end){
//这个比较长,其实就是将这两个合并。
newInterval = new Interval(Math.min(newInterval.start,intervals.get(i).start),Math.max(newInterval.end,intervals.get(i).end));
}
}
list.add(newInterval);
return list;
}
}
57. Insert Interval
最新推荐文章于 2019-05-14 22:21:01 发布