[LeetCode]Insert Interval

Insert Interval

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

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

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].code

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

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

分析

這道題一眼看過去思路很簡單,可是一遍無bug並不容易,注意別越界,而後分別找到插入的區間左右邊界分別插到哪一個區間便可。io

複雜度

time: O(n), space: O(1)class

代碼

public class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> res = new ArrayList<>();
        int i = 0;
        
        // 沒有重疊的區間,直接添加
        while (i < intervals.size() && intervals.get(i).end < newInterval.start) {
            res.add(intervals.get(i++));
        }
        
        // 對於有重疊的區間,更新start
        if (i < intervals.size()) 
            newInterval.start = Math.min(newInterval.start, intervals.get(i).start);
        
        // 對於插入的區間可以覆蓋的區間,直接跳過
        while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
            i++;
        }
        
        // 更新插入區間的end
        if (i - 1 >= 0) {
            newInterval.end = Math.max(newInterval.end, intervals.get(i - 1).end);
        }
        res.add(newInterval); // 添加更新後的插入區間
        
        // 繼續添加剩下不受影響的區間
        while (i < intervals.size()) {
            res.add(intervals.get(i++));
        }
        return res;
    }
}
相關文章
相關標籤/搜索