Data Stream as Disjoint Intervals

ㅋㅋ·2023년 1월 28일
0

알고리즘-leetcode

목록 보기
99/135

정수들을 하나씩 입력 받으면 데이터들을 통하여

연속되는 구간들을 2차원 벡터로 만들어 번환할 수 있는 자료 구조를 구현하는 문제

class SummaryRanges {
public:
    SummaryRanges() {
        
    }
    
    void addNum(int value) {

        pair<int, int> temp{value, value};
        auto back{intervals.lower_bound(temp)};

        if (back != intervals.begin())
        {
            auto front{prev(back)}; 
            if (value <= front->second)
            {
                return;
            }
            else if (value == front->second + 1)
            {
                temp.first = front->first;

                intervals.erase(front);
            }
        }

        if (back != intervals.end())
        {
            if (back->first <= value)
            {
                return;
            }
            else if (value == back->first - 1)
            {
                temp.second = back->second;

                intervals.erase(back);
            }
        }
        
        intervals.insert(move(temp));
    }
    
    vector<vector<int>> getIntervals() {

        vector<vector<int>> result{};
        for (auto it = intervals.begin(); it != intervals.end(); ++it)
        {
            result.push_back({it->first, it->second});
        }

        return result;
    }

private:
    set<pair<int, int>> intervals{};
};

/**
 * Your SummaryRanges object will be instantiated and called as such:
 * SummaryRanges* obj = new SummaryRanges();
 * obj->addNum(value);
 * vector<vector<int>> param_2 = obj->getIntervals();
 */

0개의 댓글