LeetCode228——Summary Ranges

一个月没写C++代码,现在感到好陌生

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.

vector<string> summaryRanges(vector<int>& nums) {
    vector<string> vs;
    if (nums.size() == 0) return vs; 
    int begin = nums[0];
    int end = nums[0];
    char temp[256];
    for (int i = 1; i < nums.size(); i++){
        if (nums[i] != end+1) {
            if (begin != end) {
                sprintf(temp, "%d->%d", begin, end);
            }else {
                sprintf(temp, "%d",end);
            }
            string s(temp);
            vs.push_back(s);
            begin = nums[i];
        }
        end = nums[i];
    }
    if (begin != end) {
        sprintf(temp, "%d->%d", begin, end);
    }else {
        sprintf(temp, "%d",end);
    }
    string s(temp);
    vs.push_back(s);
    return vs;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/booirror/article/details/46810977
文章标签: Leetcode
个人分类: 面试题算法题
想对作者说点什么? 我来说一句

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

关闭
关闭
关闭