当前位置:网站首页>力扣:56. 合并区间
力扣:56. 合并区间
2022-07-31 14:46:00 【empty__barrel】
- 重叠区间放在一起,合并重叠区间入数组
- 【0】先序排列重叠区间放在一起,这个问题有两种解决方案
- 直接入:将重叠区间第一个值入数组,通过重叠区间的比较更新这个值
- 最后入:遍历重叠区间所有值,当遇到第一个重叠区间第一个值,将上个重叠区间记录的fir,sec入数组。
显而易见直接入更好
代码一:直接入
class Solution {
public:
static bool comparev(vector<int>& a,vector<int>&b){
return a[0] < b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size() == 0) return intervals;
vector<vector<int>> result;
sort(intervals.begin(), intervals.end(), comparev);
result.push_back(intervals[0]);
for(int i = 1; i < intervals.size() ; i++){
if(intervals[i][0] <= result.back()[1]){
if(intervals[i][1] > result.back()[1]) result.back()[1] = intervals[i][1];
}
else{
result.push_back(intervals[i]);
}
}
return result;
}
};
代码二:间接入
class Solution {
public:
static bool comparev(vector<int>& a,vector<int>&b){
return a[0] < b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size() == 0) return intervals;
vector<vector<int>> result;
sort(intervals.begin(), intervals.end(), comparev);
int fir = intervals[0][0];
int sec = intervals[0][1];
//result.push_back(intervals[0]);
for(int i = 1; i < intervals.size() ; i++){
if(intervals[i][0] <= sec){
if(intervals[i][1] > sec) sec = intervals[i][1];
}
else{
intervals[i-1][0] = fir;
intervals[i-1][1] = sec;
result.push_back(intervals[i-1]);
fir = intervals[i][0];
sec = intervals[i][1];
}
}
// int q = intervals.size()-1;
intervals[0][0] = fir;
intervals[0][1] = sec;
result.push_back(intervals[0]);
return result;
}
};
边栏推荐
- 公告
- OAuth2:搭建授权服务器
- OpenShift 4 - Deploy Redis Cluster with Operator
- OAuth2:使用JWT令牌
- UnityShader入门学习(三)——Unity的Shader
- el-tooltip的使用
- 2021 OWASP TOP 10 漏洞指南
- Getting started with UnityShader (1) - GPU and Shader
- Analysis of the startup source code of hyperf (2) - how the request reaches the controller
- 蔚来杯2022牛客暑期多校训练营4
猜你喜欢
“听我说谢谢你”还能用古诗来说?清华搞了个“据意查句”神器,一键搜索你想要的名言警句...
MySQL 23道经典面试吊打面试官
Architecture actual combat battalion module 8 message queue table structure design
以后面试官问你 为啥不建议使用Select *,请你大声回答他!
Miller_Rabin Miller Rabin probability sieve [template]
2021 OWASP TOP 10 Vulnerability Guide
IDEA connects to MySQL database and uses data
海康摄像机取流RTSP地址规则说明
Sentinel热点参数限流
2021 OWASP TOP 10 漏洞指南
随机推荐
C language basic practice (nine-nine multiplication table) and printing different asterisk patterns
ML, DL, CV common problems sorting
2021 OWASP TOP 10 Vulnerability Guide
Prometheus之node_exporter性能监控信息采集含义
为什么要分库分表?
Node version switching management using NVM
三角恒等变换公式
微服务架构选型
UnityShader入门学习(二)——渲染流水线
ML、DL、CV常见的问题整理
Numbers that appear only once in LeetCode
BigDecimal 简介,常用方法
看交互设计如何集成到Scrum敏捷流程中
公告
How to clean up the lodash.memoize cache in the element-plus virtual table virtual-list component?
Miller_Rabin Miller Rabin probability sieve [template]
梅克尔工作室-第一次
The use of thread pool two
“听我说谢谢你”还能用古诗来说?清华搞了个“据意查句”神器,一键搜索你想要的名言警句...
Analysis of the startup source code of hyperf (2) - how the request reaches the controller