Problem
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].Solution with new list
class Solution { public Listinsert(List intervals, Interval itvl) { List res = new ArrayList<>(); if (intervals == null || intervals.size() == 0) { intervals.add(itvl); return intervals; } int i = 0; while (i < intervals.size() && intervals.get(i).end < itvl.start) { res.add(intervals.get(i++)); } while (i < intervals.size() && intervals.get(i).start <= itvl.end) { itvl.start = Math.min(intervals.get(i).start, itvl.start); itvl.end = Math.max(intervals.get(i).end, itvl.end); i++; } res.add(itvl); while (i < intervals.size()) { res.add(intervals.get(i++)); } return res; }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/77070.html
摘要:我們只要把所有和該有重疊的合并到一起就行了。最后把前半部分的列表,合并后的大和后半部分的列表連起來,就是結果了。 Merge Intervals 最新更新請見 https://yanjia.me/zh/2019/02/... Given a collection of intervals, merge all overlapping intervals.For example, Gi...
摘要:問題描述分析這道題的關鍵在于理解問題,抽取原型,理解中間可以部分如何界定,以及非部分如何進行追加。需要注意的是循環到最后一個元素和在最后一個元素的區別。 問題描述: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You m...
摘要:題目要求給定一組順序排列且相互之間沒有重疊的區間,輸入一個區間,將它插入到當前的區間數組中,并且將需要合并的區間合并,之后返回插入并且合并后的區間。我們將這三個類型的區間分別標注為類型,類型,類型。 題目要求 Given a set of non-overlapping intervals, insert a new interval into the intervals (merge...
57. Insert Interval 題目鏈接:https://leetcode.com/problems... public class Solution { public List insert(List intervals, Interval newInterval) { // skip intervals which not overlap with new on...
摘要:題目要求假設一個二維的整數數組中每一行表示一個區間,每一行的第一個值表示區間的左邊界,第二個值表示區間的右邊界。 題目要求 Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal ...
閱讀 1523·2021-08-09 13:47
閱讀 2781·2019-08-30 15:55
閱讀 3506·2019-08-29 15:42
閱讀 1127·2019-08-29 13:45
閱讀 3019·2019-08-29 12:33
閱讀 1753·2019-08-26 11:58
閱讀 995·2019-08-26 10:19
閱讀 2423·2019-08-23 18:00