Easy to Understand C++ Code


  • 5
    H
    vector<string> summaryRanges(vector<int>& nums) {
            vector<string> ret;
            string str;
            if(nums.size()==0)
                return ret;
            int start = nums[0];   
            int end=0;
            for(int i=1;i<nums.size();i++){
                str = to_string(start);
                if(nums[i]==nums[i-1]+1)
                    end = nums[i];
                if(nums[i]!=nums[i-1]+1){
                    if(end != 0)
                        str = str + "->" + to_string(end);
                    ret.push_back(str);
                    start = nums[i];
                    end = 0;
                }
            }
            if(end!=0)
                str = to_string(start) + "->" + to_string(end);
            if(end==0)
                str = to_string(start);
            ret.push_back(str);
            return ret;
        }

Log in to reply
 

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