228. 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"].

Credits:

==============

题目,返回数组范围的  集合.

思路:

模拟整个过程,利用标准库中提供了to_string函数,

就没有什么大问题.

============

code如下:

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> re;
        if(nums.empty()) return re;
        int n = nums.size();
        for(int i = 0;i<n;){
            //string tt = to_string(nums[i]);
            string t = to_string(nums[i])+"->";
            int j = i+1;
            while(j<n && nums[j]==nums[j-1]+1){
                j++;
            }
            if(i==(n-1) || j==(i+1)){
                re.push_back(to_string(nums[i]));
            }else{
                t+=to_string(nums[j-1]);
                re.push_back(t);
            }
            i = j;
        }///for
        for(auto i:re) cout<<i<<endl;
        return re;
    }
};
原文地址:https://www.cnblogs.com/li-daphne/p/5609746.html