Leetcode48: Summary Ranges

来源:互联网 发布:r软件sep“,” 编辑:程序博客网 时间:2024/06/14 23:40

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.

class Solution {public:    vector<string> summaryRanges(vector<int>& nums) {        int begin = 0;        int end = 0;        vector<string> sum;        char temp[50];        if(nums.size()<1)            return sum;        for(int i = 1; i < nums.size(); i++)        {            if(nums[i] == nums[end]+1)            {                end = i;            }            else            {                sprintf(temp, "%d", nums[begin]);                string str(temp);                if(begin != end)                {                    sprintf(temp, "%d", nums[end]);                    str+= "->" + string(temp);                }                sum.push_back(str);                begin = end = i;            }        }        sprintf(temp, "%d", nums[begin]);        string str(temp);        if(begin != end)        {            sprintf(temp, "%d", nums[end]);            str+= "->" + string(temp);        }        sum.push_back(str);        return sum;    }};

转载地址:http://blog.csdn.net/brucehb/article/details/46656089

0 0
原创粉丝点击