My accepted C++ solution


  • 0
    H

    class Solution {
    public:
    vector<string> summaryRanges(vector<int>& nums) {
    vector<string> res;
    if (nums.empty()) return res;
    string curr;
    curr += to_string(nums[0]);
    int start = 0;
    int end = 1;

        while (end < nums.size()) {
            int tmp = start;
            while (nums[end] == nums[tmp] + 1 && end < nums.size()) {
                end++;
                tmp++;
            }
            
            if (nums[tmp] != nums[start])   curr = curr + "->" + to_string(nums[tmp]);
            res.push_back(curr);
            curr.clear();
            
            if (end == nums.size()) {
                break;
            }
            else {
                start = end;
                end = start + 1;
                curr += to_string(nums[start]);
            }
            
        }
        
        if (!curr.empty())
            res.push_back(curr);
        
        return res;
    }
    

    };


Log in to reply
 

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