本文主要是介绍Data Stream as Disjoint Intervals,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
第一次用TreeSet。。。
要懂得用这种结构
/*** 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 {
TreeSet<Interval> set;/** Initialize your data structure here. */public SummaryRanges() {set = new TreeSet<>(new Comparator<Interval>(){@Overridepublic int compare(Interval a, Interval b){return a.start - b.start;}});}public void addNum(int val) {Interval temp = new Interval(val, val);Interval low = set.floor(temp);if (low != null) {if (low.end >= val) {return;} else if (low.end + 1 == val) {temp.start = low.start;set.remove(low);}}Interval high = set.higher(temp);if (high != null) {if (temp.end + 1 == high.start) {temp.end = high.end;set.remove(high);}}set.add(temp);}public List<Interval> getIntervals() {Iterator<Interval> it = set.iterator();List<Interval> list = new LinkedList<>();while (it.hasNext()) {list.add(it.next());}return list;}
}/*** Your SummaryRanges object will be instantiated and called as such:* SummaryRanges obj = new SummaryRanges();* obj.addNum(val);* List<Interval> param_2 = obj.getIntervals();*/
这篇关于Data Stream as Disjoint Intervals的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!