标签:count right int second --- 算法 first 模板 left
区间合并
解析
利用set反向存储区间,利于通过lower_bound()找到右端点大于等于left-1的区间
通过l,r合并区间,不断删除与之相交的区间
my'code
class CountIntervals {
public:
typedef pair<int,int> PII;
set<PII> heap;
int ans=0;
CountIntervals() {
}
void add(int left, int right) {
int l=left,r=right;
auto it = heap.lower_bound(PII(left-1,-2e9));
while(it!=heap.end()){
if(it->second>right+1)break;
l=min(l,it->second);
r=max(r,it->first);
ans-=it->first-it->second+1;
heap.erase(it++);
}
ans+=r-l+1;
heap.insert(PII(r,l));
}
int count() {
return ans;
}
};
/**
* Your CountIntervals object will be instantiated and called as such:
* CountIntervals* obj = new CountIntervals();
* obj->add(left,right);
* int param_2 = obj->count();
*/
模板
class section {
public:
using pii = pair<int, int>;
set<pii> s;//反向存储,{right, left} == [left, right)
uint64_t count;
section(uint64_t n = 0) :count(n) {}
int insert(const pii& x) { // 区间 [left, right)
if (x.first >= x.second)return false;
uint64_t before = count;
int addright = x.second, addleft = x.first;
for (auto p = s.lower_bound({ x.first, INT_MIN }); p != s.end() && p->second <= x.second; ) {
addright = max(addright, p->first);
addleft = min(addleft, p->second);
count -= p->first - p->second;
p = s.erase(p);
}
count += addright - addleft;
s.insert({ addright, addleft });
return count > before;
}
};
class CountIntervals {
public:
section s;
CountIntervals() {
}
void add(int left, int right) {
s.insert({left, right + 1});
}
int count() {
return s.count;
}
};
作者:MuriyaTensei
链接:https://leetcode.cn/problems/count-integers-in-intervals/solution/c-by-muriyatensei-b913/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:count,right,int,second,---,算法,first,模板,left 来源: https://www.cnblogs.com/lxp-blog/p/16273215.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。