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]
Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?
来数据了直接记录到有序集合里面,每次查询的时候,从小到大,生成区间。
每次遇到不连续的地方才需要生成区间。
TreeSet<Integer> treeset;
/** Initialize your data structure here. */
public SummaryRanges()
{
treeset=new TreeSet<>();
}
public void addNum(int val)
{
treeset.add(val);
}
public List<Interval> getIntervals()
{
ArrayList<Interval> retlist=new ArrayList<>();
int start=treeset.first();
int prenum=start-1;
for(int num :treeset)
{
if(num!=prenum+1)
{
retlist.add(new Interval(start, prenum));
start=num;
}
prenum=num;
}
retlist.add(new Interval(start, treeset.last()));
return retlist;
}