标签:
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]
.
解题思路:
这题和上一题 Merge Intervals 很像,区别就是1.原list已经根据start排序了,2.所有元素没有overlapping。反而比较简单。
1. 从头至尾遍历list,找到start比newInterval的start大的,就在它前面插入newInterval。同时跳出遍历。
2. 如果已经遍历结束,就在结尾插入newInterval。
3. 处理newInterval前面节点overlap的问题。如果newInterval不是第一个节点,看它的start和前一个节点的end,小于或等于end,就用他俩end里较大的值去更新前一个元素的end,同时将newInterval移除。同时将newInterval的前一个元素视为newInterval。
4. 处理newInterval和后面节点的overlap问题。如果newInterval的end>=后一个元素的start,用两者end的较大值去更新newInterval,同时移除后一个节点。否则跳出循环,或一直循环处理直到newInterval为最后一个节点。
/** * 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) { if(intervals.size() == 0) { intervals.add(newInterval); return intervals; } int insertIndex = 0; while(insertIndex < intervals.size()) { if(intervals.get(insertIndex).start > newInterval.start) { intervals.add(insertIndex, newInterval); break; } insertIndex++; } if(insertIndex == intervals.size()) { intervals.add(newInterval); } if(insertIndex - 1 >= 0) { if(intervals.get(insertIndex - 1).end >= newInterval.start) { intervals.get(insertIndex - 1).end = Math.max(intervals.get(insertIndex - 1).end, intervals.get(insertIndex).end); intervals.remove(insertIndex); insertIndex--; } } while(insertIndex < intervals.size() - 1 && intervals.get(insertIndex).end >= intervals.get(insertIndex + 1).start) { intervals.get(insertIndex).end = Math.max(intervals.get(insertIndex).end, intervals.get(insertIndex + 1).end); intervals.remove(insertIndex + 1); } return intervals; } }
其实插入后,直接调用 Merge Intervals 题目里的方法也可以。
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4388276.html