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>(){
            @Override
            public 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();
 */


發佈了795 篇原創文章 · 獲贊 0 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章