publicclassSummaryRanges {TreeSet<Interval> treeSet; /** Initialize your data structure here. */publicSummaryRanges() {//还是得建个comparator来按起点排序 treeSet =newTreeSet<Interval>(newComparator<Interval>() {publicintcompare(Interval in1,Interval in2) {returnin1.start-in2.start; } }); }publicvoidaddNum(int val) {Interval newInterval =newInterval(val, val);//每次插入时,首先查一下前一个相邻的区间是否有重合Interval floor =treeSet.floor(newInterval);if (floor !=null) {// if the new interval is included in the previous Interval, we don't need to insert and returnif (newInterval.start<=floor.end) {return; } elseif (newInterval.start==floor.end+1) {// if cur Interval can be combine with previous onenewInterval.start=floor.start;// we update our new intervaltreeSet.remove(floor);// remove the old one, insert the new interval later in code } }// do same thing, to check whether the next interval can be combine as wellInterval higher =treeSet.higher(newInterval);if (higher !=null) {// if so, remove old interval and update current oneif (newInterval.end+1==higher.start) {newInterval.end=higher.end;treeSet.remove(higher); } }treeSet.add(newInterval);// add the interval to current Set }publicList<Interval> getIntervals() {returnnewArrayList<Interval>(treeSet); }}