下面是我的代码。
我暂时还没有想好怎么优化,请各位大神不吝赐教!:)
/**
* 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 ArrayList insert(ArrayList intervals,
Interval newInterval) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList result = new ArrayList();
if(intervals.size() == 0){
result.add(newInterval);
return result;
}
for(Interval item:intervals){
if(item.end < newInterval.start){
result.add(item);
if(intervals.indexOf(item) == (intervals.size()-1)){
result.add(newInterval);
}
}
else if(item.start > newInterval.end){
if(!result.contains(newInterval)){
result.add(newInterval);
}
result.add(item);
}
else{
newInterval.start = Math.min(item.start, newInterval.start);
newInterval.end = Math.max(item.end, newInterval.end);
if(intervals.indexOf(item) == (intervals.size()-1)){
result.add(newInterval);
}
}
}
return result;
}
}