[Java] TreeMap + Merge Intervals with Comments (and Similar Questions for reference)
Pretty much the same as the Data Stream as Disjoint Intervals and Amount of New Area Painted Each Day.\nWe just need to maintain a tree map with non-overlapping
Pretty much the same as the [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) and [Amount of New Area Painted Each Day](https://leetcode.com/problems/amount-of-new-area-painted-each-day/).\nWe just need to maintain a tree map with non-overlapping intervals. When the new interval overlaps with any floor and ceilings, simply merge them and deduct the overlapping numbers (no need to add those numbers again).\nIn the meantime, we just need to use a global variable to record the total numbers.\n\nMore details can be found in the comments.\n\n```\nTreeMap<Integer, Integer> intervals;\nint count;\n\npublic CountIntervals() {\n    this.intervals = new TreeMap<>();\n    this.count = 0;\n}\n\npublic void add(int left, int right) {\n\t// start and end to record the merged interval\n    int start = left;\n    int end = right;\n    int toAdd = end - start + 1;\n\n    Map.Entry<Integer, Integer> floor = intervals.floorEntry(left);\n    if (floor != null) {\n        if (floor.getValue() >= end) {\n            // the entire current interval has been covered by the floor, so no new numbers need to add, simply just return.\n            return;\n        }\n        if (floor.getValue() >= start) {\n            // the current interval has been partially covered by the floor, so deduct the overlapping numbers.\n            toAdd -= floor.getValue() - start + 1;\n            intervals.remove(floor.getKey());\n            start = floor.getKey();\n        }\n    }\n\n    Map.Entry<Integer, Integer> ceiling = intervals.ceilingEntry(left);\n    // there could be multiple ceilings overlap with the current interval.\n    // e.g. current [5, 20], ceilings: [6, 8], [10, 15], [18, 22]\n    // we need to deduct the overlapping numbers properly\n    while (ceiling != null && ceiling.getKey() <= end) {\n        toAdd -= Math.min(end, ceiling.getValue()) - ceiling.getKey() + 1;\n        intervals.remove(ceiling.getKey());\n        end = Math.max(end, ceiling.getValue());\n        ceiling = intervals.ceilingEntry(left);\n    }\n    \n    // add the new numbers to the count/result.\n    count += toAdd;\n    // add the merged interval to treemap\n    intervals.put(start, end);\n}\n\npublic int count() {\n    return count;\n}\n```\n\nMy previous post on the [Amount of New Area Painted Each Day](https://leetcode.com/problems/amount-of-new-area-painted-each-day/discuss/1784268/java-treemap-merge-intervals-easy-to-understand-beats-9583) which is essentially the same as this one.
['Tree', 'Sorting']