# Insert Interval

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:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

/**
* Definition for an interval.
* public class Interval {
*     int start;
*     int end;
*     Interval() { start = 0; end = 0; }
*     Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> res = new ArrayList<Interval>();
if (intervals.size() == 0) {
return intervals;
}

int i = 0;
while (i < intervals.size() && intervals.get(i).end < newInterval.start) {
i++;
}

if (i < intervals.size()) {
newInterval.start = Math.min(intervals.get(i).start, newInterval.start);
}

while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval.end = Math.max(newInterval.end, intervals.get(i).end);
i++;
}
while(i < intervals.size()) {
i++;
}

return res;
}
}

• 本文已收录于以下专栏：

## LeetCode --- 57. Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa...
• makuiyu
• 2015年03月14日 23:10
• 1314

## Insert Interval -- LeetCode

• linhuanmars
• 2014年03月27日 01:15
• 10072

## Lintcode30 Insert Interval solution 题解

【题目描述】 Given a non-overlapping interval list which is sorted by start point.Insert a new interv...
• xuxu_ban
• 2017年04月23日 21:20
• 163

## [Java]LeetCode57 Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa...
• fumier
• 2015年08月18日 20:52
• 850

## leetCode 57.Insert Interval (插入区间) 解题思路和方法

Insert Interval  Given a set of non-overlapping intervals, insert a new interval into the interva...
• xygy8860
• 2015年07月15日 14:11
• 729

## 【LeetCode】Insert Interval 解题报告

【题目】 Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if ...
• ljiabin
• 2015年04月07日 17:28
• 1983

## 57 Insert Interval

• ChilseaSai
• 2015年10月11日 17:23
• 444

## Insert Interval

public ArrayList insert(ArrayList intervals, Interval newInterval) { // Start typing your Ja...
• qiqiqi777
• 2013年09月03日 02:33
• 320

## insert interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa...
• ststns
• 2015年01月23日 14:23
• 217

## LeetCode: Insert Interval & Merge Interval

1、Insert Interval Description: Given a set of non-overlapping intervals, the intervals were ini...
• yangfeisc
• 2015年04月14日 21:04
• 238

举报原因： 您举报文章：Insert Interval 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)