标签:class blog code java tar get
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]
.
public class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> result = new ArrayList<Interval>(); if(!intervals.isEmpty()){ int size = intervals.size(); int i = 0; while(i < size && intervals.get(i).start < newInterval.start){ ++i; } intervals.add(i, newInterval); int start = intervals.get(0).start, end = intervals.get(0).end; for(int j = 1; j < size + 1; ++j){ Interval anInterval = intervals.get(j); if(anInterval.start <= end){ end = Math.max(end, anInterval.end); } else{ result.add(new Interval(start, end)); start = anInterval.start; end = anInterval.end; } } result.add(new Interval(start, end)); } else result.add(newInterval); return result; } }
leetcode--Insert Interval,布布扣,bubuko.com
标签:class blog code java tar get
原文地址:http://www.cnblogs.com/averillzheng/p/3787566.html