Share my c++ solution using std::map


  • 0
    M

    I think my if-else condition is too much, but dont know how to reduce them. Seems that every situation should be concern about.

    /**
     * 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 {
    public:
        map<int, int> ans;
        /** Initialize your data structure here. */
        SummaryRanges() {
            
        }
        
        void addNum(int val) {
            if(ans.size() == 0){
                ans[val] = val;
            }
            auto i = ans.lower_bound(val), pre = i;
            if(i != ans.begin()){
                pre = --i;
                i++;
            }
            if(i == ans.end()){
                if(pre->second < val){
                    if(val == pre->second + 1)
                        pre->second ++;
                    else 
                        ans[val] = val;
                }
            }
            else if(i == ans.begin()){
                if(i->first == val)
                    return;
                if(i->first == val+1){
                    ans[val] = i->second;
                    ans.erase(val+1);
                }
                else ans[val] = val; 
            }
            else{
                if(val == i->first || val <= pre->second) return;
                else if(val == i->first-1 && val == pre->second+1){
                    pre->second = i->second;
                    ans.erase(i);
                }
                else if(val == i->first-1){
                    ans[val] = i->second;
                    ans.erase(i);
                }
                else if(val == pre->second+1){
                    pre->second++;
                }
                else ans[val] = val;
            }
        }
        
        vector<Interval> getIntervals() {
            vector<Interval> a;
            for(auto it = ans.begin(); it != ans.end(); ++it)
            {
                a.push_back(Interval(it->first, it->second));
            }
            return a;
        }
    };
    
    /**
     * 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.