Summary Ranges leetcode

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:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

 
vector<string> summaryRanges(vector<int>& nums) {
    vector<string> ret;
    if (nums.size() == 0)
        return ret;
    int i = 0;
    int beg = nums[i];
    while (i < nums.size())
    {
        if (i + 1 == nums.size() || nums[i+1] != nums[i] + 1)
        {
            if (nums[i] != beg)
                ret.push_back(to_string(beg) + "->" + to_string(nums[i]));
            else
                ret.push_back(to_string(beg));
            if(i + 1 < nums.size())
                beg = nums[i + 1];
        }
        i++;
    }
    return ret;
}

 

posted @ 2016-01-09 16:13  sdlwlxf  阅读(126)  评论(0编辑  收藏  举报