Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

class Solution {

public:

    vector<string> summaryRanges(vector<int>& nums) {

        

        vector<string> res;

        if(!nums.size()) return res;

        

        int i,j,left,right;

        string str;

        for(i=0;i<nums.size();i++)

        {

            left=right=nums[i];

            for(j=i+1;j<nums.size();j++)

            {

                if(nums[j]==right+1) 

                {

                    right=nums[j];

                }else

                {

                    i=j-1;break;

                }

            }

            

            if(left==right)

            {

                str=num2str(left);

            }else

            {

                str=num2str(left)+"->"+num2str(right);

            }

            res.push_back(str);

            

            if(j==nums.size()) break;

        }

        

        return res;

    }

    

    string num2str(int num)

    {

        stringstream str;

        str<<num;

        return str.str();

    }

};

//智商硬伤,一定要把语句写在break前面啊,经常忘记,怪不得死活不accept

你可能感兴趣的