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 summaryRanges(vector& nums) {
        auto n = nums.size();
        vector res;
        if (n == 0)
            return res;
        if (n == 1) {
            res.push_back(to_string(nums[0]));
            return res;
        }
        int l = nums[0], r = nums[0];
        for (int i=1; i" + to_string(r));
                l = nums[i];
            }
            r = nums[i];
            if (i == n-1) {
                if (l == r)
                    res.push_back(to_string(l));
                else
                    res.push_back(to_string(l) + "->" + to_string(r));
            }
            
        }
        return res;
    }
};

稍微改进一下,如下:

class Solution {
public:
    vector summaryRanges(vector& nums) {
        auto n = nums.size();
        vector res;
        if (n == 0)
            return res;
        if (n == 1) {
            res.push_back(to_string(nums[0]));
            return res;
        }
        int l = nums[0], r = nums[0];
        for (int i=0; i" + to_string(r));
        }
        return res;
    }
};

你可能感兴趣的:(Summary Ranges)