- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 54 lines of C++ from the credited upstream file 352.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 1 loop block detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class SummaryRanges {2 public:3 void addNum(int val) {4 if (intervals.contains(val))5 return;6 7 const int lo = lowerKey(val);8 const int hi = higherKey(val);9 10 11 12 if (lo >= 0 && hi >= 0 && intervals[lo][1] + 1 == val && val + 1 == hi) {13 intervals[lo][1] = intervals[hi][1];14 intervals.erase(hi);15 16 17 } else if (lo >= 0 && intervals[lo][1] + 1 >= val) {18 intervals[lo][1] = max(intervals[lo][1], val);19 } else if (hi >= 0 && val + 1 == hi) {20 21 intervals[val] = {val, intervals[hi][1]};22 intervals.erase(hi);23 } else {24 intervals[val] = {val, val};25 }26 }27 28 vector<vector<int>> getIntervals() {29 vector<vector<int>> res;30 for (const auto& [_, interval] : intervals)31 res.push_back(interval);32 return res;33 }34 35 private:36 map<int, vector<int>> intervals; 37 38 39 int lowerKey(int key) {40 auto it = intervals.lower_bound(key);41 if (it == intervals.begin())42 return -1;43 return (--it)->first;44 }45 46 47 int higherKey(int key) {48 const auto it = intervals.upper_bound(key);49 if (it == intervals.cend())50 return -1;51 return it->first;52 }53};54