【Leetcode】【Hard】Insert Interval

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

解题思路:

1、先用两次二分查找找到和待插入的区间有关系的区间范围;

2、将有关系的区间做处理;

3、生成新的合并后的区间并返回;

解题步骤:

代码:

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     static bool partial_order(const Interval &a, const Interval &b) {
13         return a.end < b.start;
14     };
15
16     vector<Interval> insert(std::vector<Interval> &intervals, Interval newInterval) {
17         vector<Interval>::iterator less = lower_bound(intervals.begin(), intervals.end(), newInterval, partial_order);
18         vector<Interval>::iterator greater = upper_bound(intervals.begin(), intervals.end(), newInterval, partial_order);
19
20         vector<Interval> answer;
21         answer.insert(answer.end(), intervals.begin(), less);
22         if (less < greater) {
23             newInterval.start = min(newInterval.start, (*less).start);
24             newInterval.end = max(newInterval.end, (*(greater - 1)).end);
25         }
26         answer.push_back(newInterval);
27         answer.insert(answer.end(), greater, intervals.end());
28
29         return answer;
30   }
31 };

不用lower_bound和upper_bound写的AC烂代码,留作改进:

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
13         if (intervals.empty())
14             return vector<Interval> (1, newInterval);
15         int left = 0;
16         int right = intervals.size() - 1;
17         int size = intervals.size();
18         int ins_start, ins_end;
19
20         while (left < right) {
21             int mid = (left + right) / 2;
22             if (intervals[mid].end < newInterval.start)
23                 left = mid + 1;
24             else
25                 right = mid;
26         }
27         ins_start = left;
28
29         left = left == 0 ? 0 : left - 1;
30         right = intervals.size() - 1;
31         while (left < right) {
32             int mid = (left + right) / 2 + 1;
33             if (newInterval.end < intervals[mid].start)
34                 right = mid - 1;
35             else
36                 left = mid;
37         }
38         ins_end = right;
39
40         if (ins_end == 0 && newInterval.end < intervals[0].start) {
41             intervals.insert(intervals.begin(), newInterval);
42             return intervals;
43         }
44         if (ins_start == size - 1 && newInterval.start > intervals[size - 1].end) {
45             intervals.push_back(newInterval);
46             return intervals;
47         }
48
49         vector<Interval> answer;
50         answer.insert(answer.end(), intervals.begin(), intervals.begin() + ins_start);
51         if (ins_start <= ins_end) {
52             newInterval.start = min(newInterval.start, intervals[ins_start].start);
53             newInterval.end = max(newInterval.end, intervals[ins_end].end);
54         }
55         answer.push_back(newInterval);
56         answer.insert(answer.end(), intervals.begin() + ins_end + 1, intervals.end());
57         return answer;
58
59     }
60 };
时间: 2024-10-26 09:38:43

【Leetcode】【Hard】Insert Interval的相关文章

【leetcode刷题笔记】Insert Interval

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 [

【leetcode刷题笔记】Merge Intervals

Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,10],[15,18],return [1,6],[8,10],[15,18]. 题解:首先对所有的区间按照start大小排序,然后遍历排序后的数组,用last记录前一个区间,如果遍历的当前区间可以和last合并,就把它合并到last里面:否则就把last放到answer list中,并且更新last

【leetcode刷题笔记】LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(

【leetcode刷题笔记】Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a characterb) Delete a characterc) Replace

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi