1. 程式人生 > 其它 >演算法模板---區間合併

演算法模板---區間合併

區間合併

統計區間中的整數數目

解析

利用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)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。