今天遇到一个错误,叫Output Limit Exceeded。我还特地试了一下,当ArrayList里面添加超过9147个Interval后,就会有这个错误。所以这说明我的算法有误,没能merge对Interval,导致大数据测试时爆了。
---(--)--(-)--(------)--(--)-(---)---(----)---(--)---
{----------------------------} newInterval
错误原因是只merge了第一个,其实后面那些也要遍历判断,所以最差时间是O(n),基于此,前面部分我也直接遍历过来得了,代码简单。当然采用二分肯定是更优的解法。
public class Solution { public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> ans = new ArrayList<Interval>(); int i = 0; int n = intervals.size(); while (i < n && intervals.get(i).end < newInterval.start) { ans.add(intervals.get(i)); i++; } // intervals[i].end >= newInterval.start while (i < n && intervals.get(i).start <= newInterval.end) { newInterval.start = Math.min(newInterval.start, intervals.get(i).start); newInterval.end = Math.max(newInterval.end, intervals.get(i).end); i++; } ans.add(newInterval); while (i < n) { ans.add(intervals.get(i)); i++; } return ans; } }
Python3,写的很烂。其实直接贪心添加就行。
class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: result = [] start = newInterval[0] end = newInterval[1] overlapInterval = None for interval in intervals: # if no overlapping if interval[0] > end or interval[1] < start: pass else: # overlapping if overlapInterval is None: overlapInterval = [min(start, interval[0]), max(end, interval[1])] else: overlapInterval = [min(overlapInterval[0], interval[0]), max(overlapInterval[1], interval[1])] if overlapInterval is not None: newInterval = overlapInterval inserted = False for interval in intervals: if not (interval[0] > newInterval[1] or interval[1] < newInterval[0]): # overlap continue elif (not inserted and interval[0] > newInterval[1]): result.append(newInterval) inserted = True result.append(interval) if not inserted: result.append(newInterval) return result