标签:
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).
Example
Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].
Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].
这题记得第一次刷的时候花了挺长时间做出来的,看了下九章算法上贴的答案,觉得还是那个答案写的好,如下
/** * Definition of Interval: * public classs Interval { * int start, end; * Interval(int start, int end) { * this.start = start; * this.end = end; * } */ class Solution { /** * Insert newInterval into intervals. * @param intervals: Sorted interval list. * @param newInterval: A new interval. * @return: A new sorted interval list. */ public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> result = new ArrayList<Interval>(); // write your code here if(intervals == null || newInterval == null) return null; int insertPosition = 0; for(Interval interval: intervals){ if(newInterval.start > interval.end){ result.add(interval); insertPosition++; } else if(newInterval.end < interval.start){ result.add(interval); } else{ newInterval.start = Math.min(newInterval.start, interval.start); newInterval.end= Math.max(newInterval.end, interval.end); } } result.add(insertPosition, newInterval); return result; } }
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5216765.html