Share my answer with one map C++


  • 0
    H
        class SummaryRanges {
        public:
            SummaryRanges() {
                
            }
            
            void addNum(int val) {
                if(mps.find(val) == mps.end())
                {
                     if(val == 0){
                         mps[0] = 0;
                         if(mps.find(1) != mps.end())
                             mps[0] = 1;
                     }
                     else
                     {
                        mps[val] = val;
                        if(mps.find(val-1) != mps.end())
                            mps[val-1] = val;
                        if(mps.find(val+1) != mps.end())
                            mps[val] = val+1;
                     }
                }
            }
            
            vector<Interval> getIntervals() {
                vector<Interval> res;
                for(map<int,int>::iterator it = mps.begin() ;it != mps.end() ; ){
                    
                    if(it->first == it->second){
                        Interval in(it->first,it->second);
                        res.push_back(in);
                        it ++;
                    }else
                    {
                        Interval in;
                        in.start = it->first;
                        int pre = it->second;
                        it ++;
                        while(it != mps.end() && it->first == pre){
                            pre = it->second;
                            it ++;
                        }
                        in.end = pre;
                        res.push_back(in);
                    }
                    
                }
                
                return res;
            }
        private:
             map<int,int> mps;
        };

Log in to reply
 

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