友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

57. Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

解题分析

0057 01
  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2019-10-23 12:27
 */
public int[][] insert(int[][] intervals, int[] newInterval) {
  int left = newInterval[0];
  int right = newInterval[1];
  boolean flag = false;
  List<int[]> result = new ArrayList<>();
  for (int[] ints : intervals) {
    if (right < ints[0]) {
      // 在插入区间的右侧且无交集
      if (!flag) {
        // 注意:这里是 left, right,不能直接放 newInterval
        result.add(new int[]{left, right});
        flag = true;
      }
      result.add(ints);
    } else if (ints[1] < left) {
      // 在插入区间的左侧且无交集
      result.add(ints);
    } else {
      left = Math.min(left, ints[0]);
      right = Math.max(right, ints[1]);
    }
  }
  if (!flag) {
    result.add(new int[]{left, right});
  }
  return result.toArray(new int[result.size()][2]);
}