C++ | simple solution using std::set.


  • 0
    D
    class SummaryRanges {
    private:
        set<int> m_set;
        
    public:
        /** Initialize your data structure here. */
        SummaryRanges() {
            
        }
        
        void addNum(int val) {
            m_set.insert(val);
        }
        
        vector<Interval> getIntervals() {
            vector<Interval> ret;
            if (m_set.empty()) return ret;
            
            vector<int> tmp;
            
            for (int num : m_set) {
                if (tmp.empty()) {
                    tmp.push_back(num);
                    tmp.push_back(num);
                } else if (num >= tmp[0] - 1 && num <= tmp[1] + 1) {
                    tmp[0] = min(num, tmp[0]);
                    tmp[1] = max(num, tmp[1]);
                } else {
                    ret.push_back(Interval(tmp[0], tmp[1]));
                    tmp[0] = tmp[1] = num;
                }
            }
            
            ret.push_back(Interval(tmp[0], tmp[1]));
            
            return ret;
        }
    };
    

Log in to reply
 

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