data-stream-as-disjoint-intervals

Posted 笨鸟居士的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了data-stream-as-disjoint-intervals相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/data-stream-as-disjoint-intervals/

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class SummaryRanges {
    vector<Interval> vec;
    int find(int val) {
        int vlen = vec.size();
        if (vlen == 0) {
            return -1;
        }
        int begin = 0;
        int end = vlen - 1;
        int mid;
        while (begin <= end) {
            mid = begin + (end - begin) / 2;
            // Here <= vs. >
            if (vec[mid].start > val) {
                end = mid - 1;
            }
            else {
                begin = mid + 1;
            }
        }
        // Here it‘s important to return end
        return end;
    }
    
public:
    /** Initialize your data structure here. */
    SummaryRanges() {
        
    }
    
    void addNum(int val) {
        int idx = find(val);
        if (idx < 0) {
            if (vec.size() > 0 && vec[0].start == val+1) {
                vec[0].start = val;
            }
            else {
                Interval inter(val, val);
                vec.insert(vec.begin(), inter);
            }
        }
        else {
            if (vec[idx].end == val-1) {
                vec[idx].end = val;
            }
            else if (vec[idx].end < val-1) {
                Interval inter(val, val);
                vec.insert(vec.begin()+idx+1, inter);
                idx++;
            }
            // check latter
            if (vec.size() > idx+1 && vec[idx+1].start == vec[idx].end + 1) {
                vec[idx].end = vec[idx+1].end;
                vec.erase(vec.begin()+idx+1);
            }
        }
    }
    
    vector<Interval> getIntervals() {
        return vec;
    }
};

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

 

以上是关于data-stream-as-disjoint-intervals的主要内容,如果未能解决你的问题,请参考以下文章