当前位置:网站首页>Leetcode (435) - no overlapping interval
Leetcode (435) - no overlapping interval
2022-06-25 23:30:00 【SmileGuy17】
Leetcode(435)—— No overlap
subject
Given a set of intervals intervals , among intervals[i] = [starti, endi] . return The minimum number of intervals that need to be removed , Keep the remaining intervals from overlapping .
Example 1:
Input : intervals = [[1,2],[2,3],[3,4],[1,3]]
Output : 1
explain : remove [1,3] after , There's no overlap in the rest .
Example 2:
Input : intervals = [ [1,2], [1,2], [1,2] ]
Output : 2
explain : You need to remove two [1,2] So that the rest of the intervals don't overlap .
Example 3:
Input : intervals = [ [1,2], [2,3] ]
Output : 0
explain : You don't need to remove any intervals , Because they are already non overlapping .
Tips :
- 1 1 1 <= intervals.length <= 1 0 5 10^5 105
- intervals[i].length == 2 2 2
- − 5 ∗ 1 0 4 -5 * 10^4 −5∗104 <= starti < endi <= 5 ∗ 1 0 4 5 * 10^4 5∗104
Answer key
Method 1 : Greedy Algorithm
Ideas
We might as well think about which interval to choose as the first interval .
Suppose in a certain The optimal In the selection method of , [ l k , r k ] [l_k, r_k] [lk,rk] It's the first ( That is, the leftmost ) Section , that There is no other section on its left , There are several non overlapping intervals on the right . imagine , If there is an interval [ l j , r j ] [l_j, r_j] [lj,rj], bring r j < r k r_j < r_k rj<rk, That's the interval j j j The right end of is in the interval k k k The left side of the , So we will k k k Replace with interval j j j, It does not overlap with the rest of the selected intervals on the right . And when we put the interval k k k Replace with interval j j j after , You get another kind of The optimal How to choose .
We can constantly find the new area where the right end point is on the left of the right end point of the first interval , Replace the first interval with this interval . So when we can't replace , The first interval is the one with the smallest right endpoint among all the selectable intervals . So we sort all the intervals from small to large according to the right endpoint , Then the first interval after the sequence is arranged , Is the first interval we choose .
When selecting the first interval , What if the right end points of multiple intervals are the same minimum ? Because we chose the first interval , So there is no other section on its left , It doesn't matter where the left endpoint is , We just need to select an arbitrary interval with the smallest right endpoint .
When the first interval is determined , All intervals that do not coincide with the first interval It makes up a Smaller subproblems . Because we have arranged all the intervals according to the right endpoint at the beginning , So for this sub problem , We don't have to sort again , as long as Find out the interval that does not coincide with the first interval and has the smallest right endpoint . In the same way , We can determine all subsequent intervals in turn .
In actual code writing , We traverse the intervals ordered by the right endpoint , And maintain the right endpoint of the previous selection interval in real time right \textit{right} right. If the currently traversed interval [ l i , r i ] [l_i, r_i] [li,ri] Does not coincide with the previous interval , namely l i ≥ right l_i \geq \textit{right} li≥right, Then we can greedily choose this range , And will right \textit{right} right Updated to r i r_i ri.
Code implementation
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if(intervals.empty()) return 0;
int n = intervals.size();
sort(intervals.begin(), intervals.end(),
[](vector<int>& a, vector<int>& b){
return a[1] < b[1];});
int total = 0, prev = intervals[0][1];
for(int i = 1; i < n; ++i) {
if(intervals[i][0] < prev) ++total;
else prev = intervals[i][1];
}
return total;
}
};
Complexity analysis
Time complexity : O ( n log n ) O(n \log n) O(nlogn), among n n n Is the number of intervals . We need to O ( n log n ) O(n \log n) O(nlogn) All intervals are sorted in ascending order according to the right endpoint , And need O ( n ) O(n) O(n) Time to traverse . Because the former is greater than the latter in a progressive sense , So the total time complexity is O ( n log n ) O(n \log n) O(nlogn).
Spatial complexity : O ( l o g n ) O(logn) O(logn), This is the stack space needed for sorting .
Method 2 : Dynamic programming
Ideas
Because the requirements of the topic are equivalent to 「 Choose the largest number of intervals , So that they don't overlap 」. Since the selected intervals do not overlap , So we can sort them in descending order of endpoints , And whether we sort by left endpoint or right endpoint , The results are unique .
thus , We can put all the n n n The intervals are divided into left end points ( Or right endpoint ) Sort from small to large , Then the dynamic programming method is used to calculate the maximum number of intervals . Set this after the sequence is arranged n n n The left and right endpoints of the two intervals are l 0 , ⋯ , l n − 1 l_0, \cdots, l_{n-1} l0,⋯,ln−1 as well as r 0 , ⋯ , r n − 1 r_0, \cdots, r_{n-1} r0,⋯,rn−1, Then we make f i f_i fi Express 「 From the interval 0 0 0 To the interval i i i Of these intervals , The last interval is i i i Under the circumstances , The maximum number of non overlapping intervals can be selected 」, The state transition equation is :
f i = max j < i ∧ r j ≤ l i { f j } + 1 f_i = \max_{j < i ~\wedge~ r_j \leq l_i} \{ f_j \} + 1 fi=j<i ∧ rj≤limax{ fj}+1
That is, we enumerate the number of the penultimate interval j j j, Satisfy j < i j < i j<i, And No j j j The first interval must be the same as the i i i The intervals do not overlap . Since we have sorted in ascending order by the left endpoint , So as long as the j j j The right end of an interval r j r_j rj Did not cross the i i i The left end of an interval l i l_i li, namely r j ≤ l i r_j \leq l_i rj≤li, So the first j j j The first interval is the same as the i i i The intervals do not overlap . We are in all that meet the requirements j j j in , choice f j f_j fj The largest one makes a state transition , If you can't find an interval that meets the requirements , So in the state transfer equation max \max max This item is 0 0 0, f i f_i fi for 1 1 1.
The final answer is all f i f_i fi Maximum of .
Code implementation
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if (intervals.empty()) {
return 0;
}
sort(intervals.begin(), intervals.end(), [](const auto& u, const auto& v) {
return u[0] < v[0];
});
int n = intervals.size();
vector<int> f(n, 1);
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (intervals[j][1] <= intervals[i][0]) {
f[i] = max(f[i], f[j] + 1);
}
}
}
return n - *max_element(f.begin(), f.end());
}
};
Complexity analysis
Time complexity : O ( n 2 ) O(n^2) O(n2), among n n n Is the number of intervals . We need to O ( n log n ) O(n \log n) O(nlogn) All intervals are sorted in ascending order according to the left endpoint , And need O ( n 2 ) O(n^2) O(n2) Time for dynamic planning . Because the former is smaller than the latter in the progressive sense , So the total time complexity is O ( n 2 ) O(n^2) O(n2).
Note that method two is essentially a 「 Longest ascending subsequence 」 problem , So we can optimize the time complexity to O ( n log n ) O(n \log n) O(nlogn), For details, please refer to 「300. The official solution of the longest increasing subsequence 」.
Spatial complexity : O ( n ) O(n) O(n), That is to store all States f i f_i fi The space needed .
边栏推荐
- Paper notes: multi tag learning MSWl
- App new function launch
- pdm导入vscode的实现方式
- jdbc常见异常及错误解决办法汇总
- Implementation of importing vscode from PDM
- Technology blog site collection
- LM small programmable controller software (based on CoDeSys) note XVII: PTO pulse function block
- Idea shortcut
- 分享一个OSGeo4W64下载好的库,基于qgis3.10的
- 指针强化与提高
猜你喜欢

The first public available pytorch version alphafold2 is reproduced, and Columbia University is open source openfold, with more than 1000 stars

After xampp restarts, the MySQL service cannot be started.

Beacon realizes asset management and indoor positioning based on 5.2 ultra-low power Bluetooth module efr32 (bg22ax)

hiberate实体类CURD、事务操作汇总

百度:2022年十大热度攀升专业出炉,第一名无悬念!

The applet draws a simple pie chart

UE4_UE5結合offline voice recognition插件做語音識別功能
![[opencv450 samples] inpaint restores the selected region in the image using the region neighborhood](/img/36/8ad6034473382f66f315eb70440711.png)
[opencv450 samples] inpaint restores the selected region in the image using the region neighborhood

UE4\UE5 蓝图节点Delay与Retriggerable Delay的使用与区别

指针强化与提高
随机推荐
OpenJudge NOI 2.1 15:Counterfeit Dollar
Go语言逃逸分析全纪录
Xampp重启后,MySQL服务就启动不了。
【无标题】打开一个项目连接,无法正常显示时,ping一下ip
做接口测试,这3种工具到底什么时候用?
Transformers load pre training model
CDN加速是什么
记一次beego通过go get命令后找不到bee.exe的坑
Actual combat: how to quickly change font color in typera (blog sharing - perfect) -2022.6.25 (solved)
RepOptimizer: 其实是RepVGG2
Day4 branch and loop summary and operation
cookie、session、token
Oracle -- table operation
软件测试面试一直挂,面试官总是说逻辑思维混乱,怎么办?
Implementation of importing vscode from PDM
golang Make a list of intervals with sequential numbers
qtcreator 格式化代码
Comp212 distributed protocol
Efr32bg22 ble module (low power Bluetooth communication module) at command test
leetcode_ 136_ A number that appears only once