C++ Solution, easy to understand


  • 0
    J
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> ret;
            if(nums.empty()) return ret;
            if(nums.size() == 1) return {to_string(nums.back())};
            
            int i = 0;
            for(int j = 1; j < nums.size(); j++){
                if(nums[j] - nums[i] != j - i){
                    if(j-i == 1)
                        ret.push_back(to_string(nums[i]));
                    else
                        ret.push_back(to_string(nums[i])+"->"+to_string(nums[j-1]));
                    
                    i = j;
                }
            }
            
            if(i+1 == nums.size())
                ret.push_back(to_string(nums[i]));
            else
                ret.push_back(to_string(nums[i]) + "->" + to_string(nums.back()));
            return ret;
            
        }
    };
    

Log in to reply
 

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