|
| 1 | +# [Insert Interval][title] |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +Given a set of *non-overlapping* intervals, insert a new interval into the intervals (merge if necessary). |
| 6 | + |
| 7 | +You may assume that the intervals were initially sorted according to their start times. |
| 8 | + |
| 9 | +**Example 1:** |
| 10 | +Given intervals `[1,3],[6,9]`, insert and merge `[2,5]` in as `[1,5],[6,9]`. |
| 11 | + |
| 12 | +**Example 2:** |
| 13 | +Given `[1,2],[3,5],[6,7],[8,10],[12,16]`, insert and merge `[4,9]` in as `[1,2],[3,10],[12,16]`. |
| 14 | + |
| 15 | +This is because the new interval `[4,9]` overlaps with `[3,5],[6,7],[8,10]`. |
| 16 | + |
| 17 | +**Tags:** Array, Sort |
| 18 | + |
| 19 | + |
| 20 | +## 思路 |
| 21 | + |
| 22 | +题意是给你一组有序区间,和一个待插入区间,让你待插入区间插入到前面的区间中,我们分三步走: |
| 23 | +1. 首先把有序区间中小于待插入区间的部分加入到结果中; |
| 24 | +2. 其次是插入待插入区间,如果有交集的话取两者交集的端点值; |
| 25 | +3. 最后把有序区间中大于待插入区间的部分加入到结果中; |
| 26 | + |
| 27 | +```java |
| 28 | +/** |
| 29 | + * Definition for an interval. |
| 30 | + * public class Interval { |
| 31 | + * int start; |
| 32 | + * int end; |
| 33 | + * Interval() { start = 0; end = 0; } |
| 34 | + * Interval(int s, int e) { start = s; end = e; } |
| 35 | + * } |
| 36 | + */ |
| 37 | +class Solution { |
| 38 | + public List<Interval> insert(List<Interval> intervals, Interval newInterval) { |
| 39 | + if (intervals.isEmpty()) return Collections.singletonList(newInterval); |
| 40 | + List<Interval> ans = new ArrayList<>(); |
| 41 | + int i = 0, len = intervals.size(); |
| 42 | + for (; i < len; ++i) { |
| 43 | + Interval interval = intervals.get(i); |
| 44 | + if (interval.end < newInterval.start) ans.add(interval); |
| 45 | + else break; |
| 46 | + } |
| 47 | + for (; i < len; ++i) { |
| 48 | + Interval interval = intervals.get(i); |
| 49 | + if (interval.start <= newInterval.end) { |
| 50 | + newInterval.start = Math.min(newInterval.start, interval.start); |
| 51 | + newInterval.end = Math.max(newInterval.end, interval.end); |
| 52 | + } else break; |
| 53 | + } |
| 54 | + ans.add(newInterval); |
| 55 | + for (; i < len; ++i) { |
| 56 | + ans.add(intervals.get(i)); |
| 57 | + } |
| 58 | + return ans; |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | + |
| 64 | +## 结语 |
| 65 | + |
| 66 | +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | +[title]: https://leetcode.com/problems/insert-interval |
| 71 | +[ajl]: https://github.com/Blankj/awesome-java-leetcode |
0 commit comments