A slow o(n) toy solution for fun...


  • 0
    W
    class SummaryRanges {
    	set<int> s;
    public:
    	SummaryRanges() {
    
    	}
    
    	void addNum(int val) {
    		s.insert(val);
    	}
    
    	vector<Interval> getIntervals() {
    		vector<Interval> result;
    		int last = -1;
    		Interval inval; 
    		for (auto it = s.begin(); it != s.end(); ++it)
    		{
    			if (last == -1) {
    				inval.start = inval.end = *it;
    				last = *it;
    			}
    			else {
    				if (last + 1 == *it) {
    					inval.end = *it;
    					last = *it;
    				}
    				else {
    					result.push_back(inval);
    					inval.start = inval.end = *it;
    					last = *it;
    				}
    			}
    		}
    		result.push_back(inval);
    		return result;
    	}
    };

Log in to reply
 

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