[Leetcode]228. Summary Ranges

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunhero2010/article/details/51969850

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() == 0)
            return res;
        int start = nums[0];
        int end = nums[0];
        for (int i = 1; i <=nums.size(); ++i) {
            if (i < nums.size() && nums[i] == end + 1)
                end = nums[i];
            else {
                auto str = to_string(start);
                if (start != end)
                    str.append("->" + to_string(end));
                res.emplace_back(str);
                if (i < nums.size())
                    start = end = nums[i];
            }
        }
        return res;
    }
};
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页