My concise C++ solution


  • 0
    Z
    class Solution {
    public:
    vector<string> summaryRanges(vector<int>& nums) {
        
        vector<string> res;
        if (nums.size() == 0) return res;
        
        
        int pos = 0;
        while(pos <nums.size())
        {
            string cur;
            int p = pos +1;
            cur += to_string(nums[pos]);
            while(p < nums.size() && nums[p] == (nums[p-1] + 1))
            {
                p++;
            }
            
            if (p!= (pos + 1))
            {
                cur += "->";
                cur += to_string(nums[p-1]);
            }
            res.push_back(cur);
            
            pos = p;
        }
        
        
        
        
        return res;
    }
    };

  • 0
    J
    class Solution {    
    public:
    string intToString(int x){
        stringstream s;
        s<<x;
        string tmp;
        s>>tmp;
        return tmp;
    }
    vector<string> summaryRanges(vector<int>& nums) {
        int size = nums.size();
        int i=0,j=0;
        vector<string> vec;
        for(;i<size;i++){
           if(i+1<size&&nums[i+1]==nums[i]+1)continue;
           if(i==j)
           {
               vec.push_back(intToString(nums[i]));
               j=i+1;
           }
           else{
               string s=intToString(nums[j])+"->"+intToString(nums[i]);
               vec.push_back(s);
               j=i+1;
           }
    
        }
        return vec;
    
    }
    };

Log in to reply
 

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