MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/hard/_0057/Solution.java:17–46  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2017/10/24 desc :

Source from the content-addressed store, hash-verified

15 * </pre>
16 */
17public class Solution {
18 public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
19 if (intervals.isEmpty()) return Collections.singletonList(newInterval);
20 List<Interval> ans = new ArrayList<>();
21 int i = 0, len = intervals.size();
22 for (; i < len; ++i) {
23 Interval interval = intervals.get(i);
24 if (interval.end < newInterval.start) ans.add(interval);
25 else break;
26 }
27 for (; i < len; ++i) {
28 Interval interval = intervals.get(i);
29 if (interval.start <= newInterval.end) {
30 newInterval.start = Math.min(newInterval.start, interval.start);
31 newInterval.end = Math.max(newInterval.end, interval.end);
32 } else break;
33 }
34 ans.add(newInterval);
35 for (; i < len; ++i) {
36 ans.add(intervals.get(i));
37 }
38 return ans;
39 }
40
41 public static void main(String[] args) {
42 Solution solution = new Solution();
43 Interval.print(solution.insert(Interval.createTestData("[1,3],[6,9]"), new Interval(2, 5)));
44 Interval.print(solution.insert(Interval.createTestData("[1,2],[3,5],[6,7],[8,10],[12,16]"), new Interval(4, 9)));
45 }
46}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected