C++ solution with no post-processing after main loop


  • 0
    B
    typedef std::pair<int, int> Range;
    typedef std::vector<std::string> StringVec;
    
    StringVec
    summaryRanges(std::vector<int>& nums) 
    {
        StringVec ret;
        int N = nums.size();
        bool inRange = false;
        Range range;
    
        for (int i = 0; i < N; ++i) {
            if (i != (N-1) && nums[i] == (nums[i+1] - 1)) {
                if (!inRange) {
                    inRange = true;
                    range.first = nums[i];
                }
            } else {
                std::stringstream ss;
    
                if (inRange) {
                    inRange = false;
                    range.second = nums[i];
    
                    ss << range.first;
                    ss << "->";
                    ss << range.second;
    
                } else {
                    ss << nums[i];
                }
                ret.push_back(ss.str());
            }
        }
    
        return ret;
    }

Log in to reply
 

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