Count Integers in Intervals LeetCode solution in C++
1class CountIntervals {2set<pair<int, int>> st;3int cnt;45public:6CountIntervals() {7cnt = 0;8}910void add(int left, int right) {11auto it = st.upper_bound({left, INT_MIN});1213if (it != st.begin() && (--it)->second < left) {14++it;15}1617while (it != st.end() && it->first <= right) {18left = min(left, it->first);19right = max(right, it->second);2021cnt -= (it->second - it->first + 1);22it = st.erase(it);23}2425st.insert({left, right});26cnt += (right - left + 1);27}2829int count() {30return cnt;31}32};