[leetcode]57. Insert Interval插入区间

时间:2024-10-01 20:03:26

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]]

题目

给定一堆区间,插入一个新区间。

思路

代码

 class Solution {
     public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
          List<Interval> result = new ArrayList<Interval>();
         for (Interval i : intervals) {
             // non-overlapping      | i |--|newInterval|
             if (newInterval == null || i.end < newInterval.start){
                 result.add(i);
             }
             //non-overlapping   |newInterval|--| i |
             else if (i.start > newInterval.end) {
                 result.add(newInterval);
                 result.add(i);
                 newInterval = null;// guarantee not entring if (newInterval != null)
             }
             // overlapping, update start and end
             else {
                 newInterval.start = Math.min(newInterval.start, i.start);
                 newInterval.end = Math.max(newInterval.end, i.end);
             }
         }
         if (newInterval != null)
             result.add(newInterval);
         return result;
     }
 }