## 题目描述：

LeetCode 352. Data Stream as Disjoint Intervals

Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.

For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:

```[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
```

What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?

## 解题思路：

TreeSet底层使用红黑树实现，可以用log(n)的代价实现元素查找。

## Java代码：

``````/**
* Definition for an interval.
* public class Interval {
*     int start;
*     int end;
*     Interval() { start = 0; end = 0; }
*     Interval(int s, int e) { start = s; end = e; }
* }
*/
public class SummaryRanges {

/** Initialize your data structure here. */

private TreeSet<Interval> intervalSet;

public SummaryRanges() {
intervalSet = new TreeSet<Interval>(new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
}

Interval valInterval = new Interval(val, val);
Interval floor = intervalSet.floor(valInterval);
if (floor != null) {
if (floor.end >= val) {
return;
} else if (floor.end + 1 == val) {
valInterval.start = floor.start;
intervalSet.remove(floor);
}
}
Interval higher = intervalSet.higher(valInterval);
if (higher != null && higher.start == val + 1) {
valInterval.end = higher.end;
intervalSet.remove(higher);
}
}

public List<Interval> getIntervals() {
return Arrays.asList(intervalSet.toArray(new Interval[0]));
}
}

/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* List<Interval> param_2 = obj.getIntervals();
*/
``````

Pingbacks已关闭。

1. cak199164 发布于 2016年6月1日 04:56 #

书影大神,为什么这里没有几道序号100以内的老题解法呢?

2. 在线疯狂 发布于 2016年6月2日 17:07 #

那些题目的解法还没有来得及补全，后面抽时间逐一增补。