码迷,mamicode.com
首页 > 其他好文 > 详细

data-stream-as-disjoint-intervals

时间:2016-06-01 01:31:24      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5548165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!