0ms Cpp Solution (easy to understand)


  • 0
    I

    Basically What I am doing is checking if the next character in our vector is the next greater element, that is I am checking if nums[i]==nums[i+1]. Although the code is easy to impliment and understand, but if any doubt, then feel free to ask.

    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums)
        {
        vector<string> ans;
        if(nums.size()==0)
            return ans;
        for(int i=0; i<nums.size();)
        {
            string range_start, range_end;
            range_start=to_string(nums[i]);
            for(int j=i+1; j<nums.size() && nums[j]==nums[i]+1; j++, i++);
            range_end=to_string(nums[i]);
            string temp;
            if(range_start != range_end)
            {
                temp=range_start+"->"+range_end;
            }
            else 
                temp=range_start;
            ans.push_back(temp);
            i++;
        }
        return ans;
    }
    };

Log in to reply
 

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