[Leetcode]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"].

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;
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunhero2010/article/details/51969850
文章标签: leetcode
个人分类: LeetCode
上一篇[leetcode]229. Majority Element II
下一篇[Leetcode]216. Combination Sum III
想对作者说点什么? 我来说一句

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

关闭
关闭
关闭