Summary Ranges 连续的数组格式化输出

来源:互联网 发布:淘宝店代理货源 编辑:程序博客网 时间:2024/06/03 06:58

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

class Solution {public://nums数组是有负数的,所以(char)(nums[i]+'0')错误//char buf[10];sprintf(buf, "%d", 100);string b = buf;    vector<string> summaryRanges(vector<int>& nums) {                vector<string> res;        int len=nums.size();        if(len==0)            return res;        for(int i=0,j=0;i<len;)        {            char buf[10];            sprintf(buf,"%d",nums[i]);            string path=buf;                        j=++i;            while(j<len&&nums[j]==nums[j-1]+1)                j++;            if(j==i){                res.push_back(path);            }else {                path+="->";                                char buf[10];                sprintf(buf,"%d",nums[j-1]);                string tmp=buf;                                path+=tmp;                res.push_back(path);            }            i=j;        }        return res;    }};

0 0