C++ code, plain puzzle with no tricks, nothing special


  • 0
    J
    std::vector<std::string> summaryRanges(std::vector<int>& nums) {
        vector<string> result;
        if(nums.size()==0) return result;
        int begin = 0;
        for (int i=1; i<nums.size(); i++) {
            if (nums[i]!=nums[i-1]+1) {
                if (i-begin>1) {
                    string thisString = to_string(nums[begin]) + "->" + to_string(nums[i-1]);
                    result.push_back(thisString);
                } else result.push_back(to_string(nums[begin]));
                begin = i;
            }
        }
        if(begin==nums.size()-1) result.push_back(to_string(nums[begin]));
        else {
            string thisString = to_string(nums[begin]) + "->" + to_string(nums[nums.size()-1]);
            result.push_back(thisString);
        }
        return result;
    }

Log in to reply
 

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