JAVA | TreeMap
\nclass CountIntervals {\n    TreeMap<Integer,Integer> map;\n    int count=0;\n    public CountIntervals() {\n        map=new TreeMap<>();\n    }\n    \n    pub
```\nclass CountIntervals {\n    TreeMap<Integer,Integer> map;\n    int count=0;\n    public CountIntervals() {\n        map=new TreeMap<>();\n    }\n    \n    public void add(int left, int right) {\n        int l=left;\n        int r=right;\n        \n        while(true){\n            if(map.floorKey(r)==null || map.get(map.floorKey(r))<l)\n                break;\n            \n            int prevLeft=map.floorKey(r);\n            int prevRight=map.get(prevLeft);\n            \n            count-=(prevRight-prevLeft+1);\n            map.remove(prevLeft);\n            \n            l=Math.min(l,prevLeft);\n            r=Math.max(r,prevRight);\n        }\n        \n        map.put(l,r);\n        count+=(r-l+1);\n    }\n    \n    public int count() {\n        return count;\n    }\n}\n\n```
['Tree', 'Java']