14 lines c++ solution using ostringstream


  • 0
    Z
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> res;
            if(nums.empty())return res;
            ostringstream out;
            int n=nums.size();
            nums.push_back(nums[n-1]);
            for(int i=0;i<n;i++){
                if(nums[i]+1!=nums[i+1]){
                    if(out.str()=="")out<<nums[i];
                    else out<<"->"<<nums[i]; 
                    res.push_back(out.str());
                    out.str("");   //clear
                }
                else if(out.str()=="")out<<nums[i];
            }
            return res;
        }
    };

Log in to reply
 

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