标签:dex you github https find pac public zhang for
57 Insert Interval https://www.youtube.com/watch?v=oWHWDI2eOHY Sol1: use 56, insert this new interval into the sorted list, since its sorted already No need to sort it again, so the time complexiy is o(n), for merging Space is still o(n) class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval) { // find the right index to insert the new interval into the intervals int s = newInterval.start; int index = 0; for(Interval interval : intervals){ if (interval.start <= s){ index++; } } intervals.add(index, newInterval); List<Interval> result = new ArrayList<>(); int start = intervals.get(0).start; int end = intervals.get(0).end; for(Interval interval : intervals){ if(interval.start <= end){ end = Math.max(end, interval.end); }else{ result.add(new Interval(start, end)); start = interval.start; end = interval.end; } } result.add(new Interval(start, end)); return result; } } Sol2: 很多人都用这个方法, 很多用while 写 我觉得用 if else 写 清楚 7:52 参考花花的代码 class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> left = new ArrayList<>(); List<Interval> right = new ArrayList<>(); int start = newInterval.start; int end = newInterval.end; for(Interval interval : intervals){ if(interval.end < start){ left.add(interval); }else if(interval.start > end){ right.add(interval); }else{ start = Math.min(start, interval.start); end = Math.max(end, interval.end); } } List<Interval> result = new ArrayList<>(); for(Interval interval : left){ result.add(interval); } result.add(new Interval(start, end)); for(Interval interval : right){ result.add(interval); } return result; } } https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/57.%20Insert%20Interval.java
标签:dex you github https find pac public zhang for
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9454895.html