Why is memory limit exceeded? (C++, map)


  • 0
    A

    This codes runs fine in small examples but produces Memory Limit Exceeded error for adding number from 1 to 2000. Can anyone point out why?
    Also it only fails when I run the whole test, not when I only run the specific test.

    class SummaryRanges {
    private:
        map<int, int> intervals;
    public:
        /** Initialize your data structure here. */
        SummaryRanges() :intervals(){
            
        }
        
        void addNum(int val) {
            auto it=intervals.upper_bound(val);
            auto it_p=it;
            if(it_p!=intervals.begin())it_p--;
            
            if(it!=intervals.end()&&it->first==val+1){
                if(it!=intervals.begin() && it_p->second==val-1){
                    int interval_first=it_p->first;
                    int interval_second=it->second;
                    it_p=intervals.erase(it_p);intervals.erase(it_p);
                    intervals[interval_first]=interval_second;
                }else{
                    int interval_second=it->second;
                    intervals.erase(it);
                    intervals[val]=interval_second;
                }
            }else if(it!=intervals.begin() && it_p->second==val-1){
                it_p->second=val;
            }else{
                intervals[val]=val;
            }
        }
        
        vector<Interval> getIntervals() {
            vector<Interval> res;
            res.reserve(intervals.size());
            for(auto p:intervals){
                res.emplace_back(p.first,p.second);
            }
            return res;
        }
    };

Log in to reply
 

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