My binary search solution


  • 0
    B

    Use binary search to find proper interval, and connect neighbor intervals if necessary.

    
    /**
     * 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();
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.